'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var path = _interopDefault(require('path'));
var managers_js = require('./managers.js');
var models_js = require('./models.js');
var buffer = require('buffer');
var stream = require('stream');
var through2 = _interopDefault(require('through2'));
var listpack = _interopDefault(require('git-list-pack'));
var peek = _interopDefault(require('buffer-peek-stream'));
var applyDelta = _interopDefault(require('git-apply-delta'));
var marky = _interopDefault(require('marky'));
var utils_js = require('./utils.js');
var pad = _interopDefault(require('pad'));
var pako = _interopDefault(require('pako'));
var crypto = _interopDefault(require('crypto'));
var openpgp_min_js = require('openpgp/dist/openpgp.min.js');

/**
 * Add a file to the git index (aka staging area)
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{workdir, gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} args.filepath - The path to the file to add to the index.
 * @returns {Promise<void>} - Resolves successfully once the git index has been updated.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * await add(repo, {filepath: 'README.md'})
 */
async function add({ gitdir, workdir, fs: _fs }, { filepath }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  const type = 'blob';
  const object = await fs$$1.read(path.join(workdir, filepath));
  if (object === null) throw new Error(`Could not read file '${filepath}'`);
  const oid = await managers_js.GitObjectManager.write({ fs: fs$$1, gitdir, type, object });
  await managers_js.GitIndexManager.acquire({ fs: fs$$1, filepath: `${gitdir}/index` }, async function (index) {
    let stats = await fs$$1._lstat(path.join(workdir, filepath));
    index.insert({ filepath, stats, oid });
  });
  // TODO: return oid?
}

/**
 * Initialize a new repository
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @returns {Promise<void>} - Resolves successfully when filesystem operations are complete.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * await init(repo)
 */
async function init({ gitdir, fs: _fs }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let folders = ['hooks', 'info', 'objects/info', 'objects/pack', 'refs/heads', 'refs/tags'];
  folders = folders.map(dir => gitdir + '/' + dir);
  await fs$$1.mkdirs(folders);
  await fs$$1.write(gitdir + '/config', '[core]\n' + '\trepositoryformatversion = 0\n' + '\tfilemode = false\n' + '\tbare = false\n' + '\tlogallrefupdates = true\n' + '\tsymlinks = false\n' + '\tignorecase = true\n');
  await fs$$1.write(gitdir + '/HEAD', 'ref: refs/heads/master\n');
}

/**
 * Read and/or write to the git config file(s)
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} args.path -  The key of the git config entry.
 * @param {string} [args.value] - A value to store at that path.
 * @returns {Promise<any>} - Resolves with the config value
 *
 * If no `value` is provided, it does a read.
 * If a `value` is provided, it does a write.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 *
 * // Write config value
 * await config(repo, {
 *   path: 'user.name',
 *   value: 'Mr. Test'
 * })
 *
 * // Read config value
 * let value = await config(repo, {
 *   path: 'user.name'
 * })
 */
async function config({ gitdir, fs: _fs }, args) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let { path: path$$1, value } = args;
  const config = await managers_js.GitConfigManager.get({ fs: fs$$1, gitdir });
  // This carefully distinguishes between
  // 1) there is no 'value' argument (do a "get")
  // 2) there is a 'value' argument with a value of undefined (do a "set")
  // Because setting a key to undefined is how we delete entries from the ini.
  if (value === undefined && !args.hasOwnProperty('value')) {
    const value = await config.get(path$$1);
    return value;
  } else {
    await config.set(path$$1, value);
    await managers_js.GitConfigManager.save({ fs: fs$$1, gitdir, config });
  }
}

/**
 * Fetch commits
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{workdir, gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} [args.url=undefined] - The URL of the remote git server. The default is the value set in the git config for that remote.
 * @param {string} [args.remote='origin'] - If `url` is not specified, determines which remote to use.
 * @param {string} [args.ref=undefined] - Which branch to fetch from. By default this is the currently checked out branch.
 * @param {string} [args.authUsername=undefined] - The username to use with Basic Auth
 * @param {string} [args.authPassword=undefined] - The password to use with Basic Auth
 * @param {integer} [args.depth=undefined] - Determines how much of the git repository's history to retrieve.
 * @param {Date} [args.since=undefined] - Only fetch commits created after the given date. Mutually exclusive with `depth`.
 * @param {string[]} [args.exclude=[]] - A list of branches or tags. Instructs the remote server not to send us any commits reachable from these refs.
 * @param {boolean} [args.relative=false] - Changes the meaning of `depth` to be measured from the current shallow depth rather than from the branch tip.
 * @param {Function} [args.onprogress=undefined] - Callback to receive [ProgressEvent](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent)s for the operation.
 * @returns {Promise<void>} - Resolves successfully when clone completes
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * await fetch(repo, {
 *   url: 'https://cors-buster-jfpactjnem.now.sh/github.com/wmhilton/isomorphic-git',
 *   depth: 1
 * })
 */
async function fetch({ gitdir, fs: fs$$1 }, {
  ref = 'HEAD',
  remote,
  url,
  authUsername,
  authPassword,
  depth,
  since,
  exclude,
  relative,
  onprogress
}) {
  let response = await fetchPackfile({
    gitdir,
    fs: fs$$1
  }, {
    ref,
    remote,
    url,
    authUsername,
    authPassword,
    depth,
    since,
    exclude,
    relative
  });
  await unpack({ fs: fs$$1, gitdir }, { inputStream: response.packfile, onprogress });
}

async function fetchPackfile({ gitdir, fs: _fs }, {
  ref,
  remote,
  url,
  authUsername,
  authPassword,
  depth = null,
  since = null,
  exclude = [],
  relative = false
}) {
  const fs$$1 = new models_js.FileSystem(_fs);
  if (depth !== null) {
    if (Number.isNaN(parseInt(depth))) {
      throw new Error(`Invalid value for depth argument: ${depth}`);
    }
    depth = parseInt(depth);
  }
  remote = remote || 'origin';
  if (url === undefined) {
    url = await config({ fs: fs$$1, gitdir }, {
      path: `remote.${remote}.url`
    });
  }
  let remoteHTTP = new managers_js.GitRemoteHTTP(url);
  if (authUsername !== undefined && authPassword !== undefined) {
    remoteHTTP.auth = {
      username: authUsername,
      password: authPassword
    };
  }
  await remoteHTTP.preparePull();
  // Check server supports shallow cloning
  if (depth !== null && !remoteHTTP.capabilities.has('shallow')) {
    throw new Error(`Remote does not support shallow fetches`);
  }
  if (since !== null && !remoteHTTP.capabilities.has('deepen-since')) {
    throw new Error(`Remote does not support shallow fetches by date`);
  }
  if (exclude.length > 0 && !remoteHTTP.capabilities.has('deepen-not')) {
    throw new Error(`Remote does not support shallow fetches excluding commits reachable by refs`);
  }
  if (relative === true && !remoteHTTP.capabilities.has('deepen-relative')) {
    throw new Error(`Remote does not support shallow fetches relative to the current shallow depth`);
  }
  await managers_js.GitRefManager.updateRemoteRefs({
    fs: fs$$1,
    gitdir,
    remote,
    refs: remoteHTTP.refs,
    symrefs: remoteHTTP.symrefs
  });
  let want = await managers_js.GitRefManager.resolve({
    fs: fs$$1,
    gitdir,
    ref: `refs/remotes/${remote}/${ref}`
  });
  // Note: I removed "ofs-delta" from the capabilities list and now
  // Github uses all ref-deltas when I fetch packfiles instead of all ofs-deltas. Nice!
  const capabilities = `multi_ack_detailed no-done side-band-64k thin-pack agent=git/${utils_js.pkg.name}@${utils_js.pkg.version}${relative ? ' deepen-relative' : ''}`;
  let packstream = new stream.PassThrough();
  packstream.write(models_js.GitPktLine.encode(`want ${want} ${capabilities}\n`));
  let oids = await managers_js.GitShallowManager.read({ fs: fs$$1, gitdir });
  if (oids.size > 0 && remoteHTTP.capabilities.has('shallow')) {
    for (let oid of oids) {
      packstream.write(models_js.GitPktLine.encode(`shallow ${oid}\n`));
    }
  }
  if (depth !== null) {
    packstream.write(models_js.GitPktLine.encode(`deepen ${depth}\n`));
  }
  if (since !== null) {
    packstream.write(models_js.GitPktLine.encode(`deepen-since ${Math.floor(since.valueOf() / 1000)}\n`));
  }
  for (let x of exclude) {
    packstream.write(models_js.GitPktLine.encode(`deepen-not ${x}\n`));
  }
  packstream.write(models_js.GitPktLine.flush());
  let have = null;
  try {
    have = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref });
  } catch (err) {}
  if (have) {
    packstream.write(models_js.GitPktLine.encode(`have ${have}\n`));
    packstream.write(models_js.GitPktLine.flush());
  }
  packstream.end(models_js.GitPktLine.encode(`done\n`));
  let response = await remoteHTTP.pull(packstream);
  response.packetlines.pipe(through2(async (data, enc, next) => {
    let line = data.toString('utf8');
    if (line.startsWith('shallow')) {
      let oid = line.slice(-41).trim();
      if (oid.length !== 40) {
        throw new Error(`non-40 character 'shallow' oid: ${oid}`);
      }
      oids.add(oid);
      await managers_js.GitShallowManager.write({ fs: fs$$1, gitdir, oids });
    } else if (line.startsWith('unshallow')) {
      let oid = line.slice(-41).trim();
      if (oid.length !== 40) {
        throw new Error(`non-40 character 'shallow' oid: ${oid}`);
      }
      oids.delete(oid);
      await managers_js.GitShallowManager.write({ fs: fs$$1, gitdir, oids });
    }
    next(null, data);
  }));
  return response;
}

const types = {
  1: 'commit',
  2: 'tree',
  3: 'blob',
  4: 'tag',
  6: 'ofs-delta',
  7: 'ref-delta'
};

function parseVarInt(buffer$$1 /*: Buffer */) {
  let n = 0;
  for (var i = 0; i < buffer$$1.byteLength; i++) {
    n = (buffer$$1[i] & 0b01111111) + (n << 7);
    if ((buffer$$1[i] & 0b10000000) === 0) {
      if (i !== buffer$$1.byteLength - 1) throw new Error('Invalid varint buffer');
      return n;
    }
  }
  throw new Error('Invalid varint buffer');
}

/**
 * @ignore
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {ReadableStream} args.inputStream
 * @param {Function} args.onprogress
 */
async function unpack({ gitdir, fs: _fs }, { inputStream, onprogress }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  return new Promise(function (resolve, reject) {
    // Read header
    peek(inputStream, 12, (err, data, inputStream) => {
      if (err) return reject(err);
      let iden = data.slice(0, 4).toString('utf8');
      if (iden !== 'PACK') {
        throw new Error(`Packfile started with '${iden}'. Expected 'PACK'`);
      }
      let ver = data.slice(4, 8).toString('hex');
      if (ver !== '00000002') {
        throw new Error(`Unknown packfile version '${ver}'. Expected 00000002.`);
      }
      // Read a 4 byte (32-bit) int
      let numObjects = data.readInt32BE(8);
      if (onprogress !== undefined) {
        onprogress({ loaded: 0, total: numObjects, lengthComputable: true });
      }
      if (numObjects === 0) return resolve();
      // And on our merry way
      let totalTime = 0;
      let totalApplyDeltaTime = 0;
      let totalWriteFileTime = 0;
      let totalReadFileTime = 0;
      let offsetMap = new Map();
      inputStream.pipe(listpack()).pipe(through2.obj(async ({ data, type, reference, offset, num }, enc, next) => {
        type = types[type];
        marky.mark(`${type} #${num} ${data.length}B`);
        if (type === 'ref-delta') {
          let oid = buffer.Buffer.from(reference).toString('hex');
          try {
            marky.mark(`readFile`);
            let { object, type } = await managers_js.GitObjectManager.read({
              fs: fs$$1,
              gitdir,
              oid
            });
            totalReadFileTime += marky.stop(`readFile`).duration;
            marky.mark(`applyDelta`);
            let result = applyDelta(data, object);
            totalApplyDeltaTime += marky.stop(`applyDelta`).duration;
            marky.mark(`writeFile`);
            let newoid = await managers_js.GitObjectManager.write({
              fs: fs$$1,
              gitdir,
              type,
              object: result
            });
            totalWriteFileTime += marky.stop(`writeFile`).duration;
            // console.log(`${type} ${newoid} ref-delta ${oid}`)
            offsetMap.set(offset, newoid);
          } catch (err) {
            throw new Error(`Could not find object ${reference} ${oid} that is referenced by a ref-delta object in packfile at byte offset ${offset}.`);
          }
        } else if (type === 'ofs-delta') {
          // Note: this might be not working because offsets might not be
          // guaranteed to be on object boundaries? In which case we'd need
          // to write the packfile to disk first, I think.
          // For now I've "solved" it by simply not advertising ofs-delta as a capability
          // during the HTTP request, so Github will only send ref-deltas not ofs-deltas.
          let absoluteOffset = offset - parseVarInt(reference);
          let referenceOid = offsetMap.get(absoluteOffset);
          // console.log(`${offset} ofs-delta ${absoluteOffset} ${referenceOid}`)
          let { type, object } = await managers_js.GitObjectManager.read({
            fs: fs$$1,
            gitdir,
            oid: referenceOid
          });
          let result = applyDelta(data, object);
          let oid = await managers_js.GitObjectManager.write({
            fs: fs$$1,
            gitdir,
            type,
            object: result
          });
          // console.log(`${offset} ${type} ${oid} ofs-delta ${referenceOid}`)
          offsetMap.set(offset, oid);
        } else {
          marky.mark(`writeFile`);
          let oid = await managers_js.GitObjectManager.write({
            fs: fs$$1,
            gitdir,
            type,
            object: data
          });
          totalWriteFileTime += marky.stop(`writeFile`).duration;
          // console.log(`${offset} ${type} ${oid}`)
          offsetMap.set(offset, oid);
        }
        if (onprogress !== undefined) {
          onprogress({
            loaded: numObjects - num,
            total: numObjects,
            lengthComputable: true
          });
        }
        let perfentry = marky.stop(`${type} #${num} ${data.length}B`);
        totalTime += perfentry.duration;
        if (num === 0) {
          console.log(`Total time unpacking objects: ${totalTime}`);
          console.log(`Total time applying deltas: ${totalApplyDeltaTime}`);
          console.log(`Total time reading files: ${totalReadFileTime}`);
          console.log(`Total time writing files: ${totalWriteFileTime}`);
          return resolve();
        }
        next(null);
      })).on('error', reject).on('finish', resolve);
    });
  });
}

async function writeTreeToDisk({ gitdir, workdir, index, prefix, tree, fs: fs$$1 }) {
  for (let entry of tree) {
    let { type, object } = await managers_js.GitObjectManager.read({
      fs: fs$$1,
      gitdir,
      oid: entry.oid
    });
    let entrypath = prefix === '' ? entry.path : `${prefix}/${entry.path}`;
    let filepath = path.join(workdir, prefix, entry.path);
    switch (type) {
      case 'blob':
        await fs$$1.write(filepath, object);
        let stats = await fs$$1._lstat(filepath);
        index.insert({
          filepath: entrypath,
          stats,
          oid: entry.oid
        });
        break;
      case 'tree':
        let tree = models_js.GitTree.from(object);
        await writeTreeToDisk({
          gitdir,
          workdir,
          index,
          prefix: entrypath,
          tree,
          fs: fs$$1
        });
        break;
      default:
        throw new Error(`Unexpected object type ${type} found in tree for '${entrypath}'`);
    }
  }
}

/**
 * Checkout a branch
 * @param {GitRepo} repo - A {@link Git} object matching `{workdir, gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} [args.remote='origin'] - What to name the remote that is created. The default is 'origin'.
 * @param {string} [args.ref=undefined] - Which branch to clone. By default this is the designated "main branch" of the repository.
 * @returns {Promise<void>} - Resolves successfully when filesystem operations are complete.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * await checkout(repo, {ref: 'master'})
 */
async function checkout({ workdir, gitdir, fs: _fs }, { remote, ref }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  // Get tree oid
  let oid;
  if (remote) {
    let remoteRef;
    if (ref === undefined) {
      remoteRef = await managers_js.GitRefManager.resolve({
        fs: fs$$1,
        gitdir,
        ref: `${remote}/HEAD`,
        depth: 2
      });
      ref = path.basename(remoteRef);
    } else {
      remoteRef = `${remote}/${ref}`;
    }
    oid = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref: remoteRef });
    // Make the remote ref our own!
    await fs$$1.write(`${gitdir}/refs/heads/${ref}`, oid + '\n');
  } else {
    if (ref === undefined) {
      throw new Error('Cannot checkout ref "undefined"');
    }
    oid = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref });
  }
  let commit = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid });
  if (commit.type !== 'commit') {
    throw new Error(`Unexpected type: ${commit.type}`);
  }
  let comm = models_js.GitCommit.from(commit.object.toString('utf8'));
  let sha = comm.headers().tree;
  // Get top-level tree
  let { type, object } = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid: sha });
  if (type !== 'tree') throw new Error(`Unexpected type: ${type}`);
  let tree = models_js.GitTree.from(object);
  // Acquire a lock on the index
  await managers_js.GitIndexManager.acquire({ fs: fs$$1, filepath: `${gitdir}/index` }, async function (index) {
    // TODO: Big optimization possible here.
    // Instead of deleting and rewriting everything, only delete files
    // that are not present in the new branch, and only write files that
    // are not in the index or are in the index but have the wrong SHA.
    for (let entry of index) {
      try {
        await fs$$1.rm(path.join(workdir, entry.path));
      } catch (err) {}
    }
    index.clear();
    // Write files. TODO: Write them atomically
    await writeTreeToDisk({ fs: fs$$1, gitdir, workdir, index, prefix: '', tree });
    // Update HEAD TODO: Handle non-branch cases
    fs$$1.write(`${gitdir}/HEAD`, `ref: refs/heads/${ref}`);
  });
}

/**
 * Clone a repository
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{workdir, gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} args.url - The URL of the remote repository.
 * @param {string} [args.remote='origin'] - What to name the remote that is created. The default is 'origin'.
 * @param {string} [args.ref=undefined] - Which branch to clone. By default this is the designated "main branch" of the repository.
 * @param {string} [args.authUsername=undefined] - The username to use with Basic Auth
 * @param {string} [args.authPassword=undefined] - The password to use with Basic Auth
 * @param {integer} [args.depth=undefined] - Determines how much of the git repository's history to retrieve.
 * @param {Date} [args.since=undefined] - Only fetch commits created after the given date. Mutually exclusive with `depth`.
 * @param {string[]} [args.exclude=[]] - A list of branches or tags. Instructs the remote server not to send us any commits reachable from these refs.
 * @param {boolean} [args.relative=false] - Changes the meaning of `depth` to be measured from the current shallow depth rather than from the branch tip.
 * @param {Function} [args.onprogress=undefined] - Callback to receive [ProgressEvent](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent)s for the operation.
 * @returns {Promise<void>} - Resolves successfully when clone completes
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * await clone(repo, {
 *   url: 'https://cors-buster-jfpactjnem.now.sh/github.com/wmhilton/isomorphic-git',
 *   depth: 1
 * })
 */
async function clone({ workdir, gitdir, fs: fs$$1 = utils_js.fs() }, {
  url,
  remote,
  ref,
  authUsername,
  authPassword,
  depth,
  since,
  exclude,
  relative,
  onprogress
}) {
  utils_js.setfs(fs$$1);
  remote = remote || 'origin';
  await init({ gitdir, fs: fs$$1 });
  // Add remote
  await config({
    gitdir,
    fs: fs$$1
  }, {
    path: `remote.${remote}.url`,
    value: url
  });
  // Fetch commits
  await fetch({
    gitdir,
    fs: fs$$1
  }, {
    ref,
    remote,
    authUsername,
    authPassword,
    depth,
    since,
    exclude,
    relative,
    onprogress
  });
  // Checkout branch
  await checkout({
    workdir,
    gitdir,
    fs: fs$$1
  }, {
    ref,
    remote
  });
}

async function constructTree({ fs: fs$$1, gitdir, inode }) /*: string */{
  // use depth first traversal
  let children = inode.children;
  for (let inode of children) {
    if (inode.type === 'tree') {
      inode.metadata.mode = '040000';
      inode.metadata.oid = await constructTree({ fs: fs$$1, gitdir, inode });
    }
  }
  let entries = children.map(inode => ({
    mode: inode.metadata.mode,
    path: inode.basename,
    oid: inode.metadata.oid,
    type: inode.type
  }));
  const tree = models_js.GitTree.from(entries);
  let oid = await managers_js.GitObjectManager.write({
    fs: fs$$1,
    gitdir,
    type: 'tree',
    object: tree.toObject()
  });
  return oid;
}

/**
 * Create a new commit
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} args.message - The commit message to use.
 * @param {Object} [args.author] - The details about the commit author.
 * @param {string} [args.author.name=undefined] - Default is `user.name` config.
 * @param {string} [args.author.email=undefined] - Default is `user.email` config.
 * @param {Date} [args.author.date=new Date()] - Set the author timestamp field. Default is the current date.
 * @param {number} [args.author.timestamp=undefined] - Set the author timestamp field. This is an alternative to using `date` using an integer number of seconds since the Unix epoch instead of a JavaScript date object.
 * @param {Object} [args.committer=author] - The details about the commit committer, in the same format as the author parameter. If not specified, the author details are used.
 * @param {string} [args.privateKeys=undefined] - A PGP private key in ASCII armor format.
 * @returns {Promise<string>} - The object ID of the newly created commit.
 * @todo Move the PGP signing to a separte signCommit function for better code splitting.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * let sha = await commit(repo, {
 *   author: {
 *     name: 'Mr. Test',
 *     email: 'mrtest@example.com'
 *   },
 *   privateKeys: '-----BEGIN PGP PRIVATE KEY BLOCK-----...',
 *   message: 'Added the a.txt file'
 * })
 */
async function commit({ gitdir, fs: _fs }, { message, author, committer, privateKeys }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  // Fill in missing arguments with default values
  if (author === undefined) author = {};
  if (author.name === undefined) {
    author.name = await config({ fs: fs$$1, gitdir, path: 'user.name' });
  }
  if (author.email === undefined) {
    author.email = await config({ fs: fs$$1, gitdir, path: 'user.email' });
  }
  committer = committer || author;
  let authorDateTime = author.date || new Date();
  let committerDateTime = committer.date || authorDateTime;
  let oid;
  await managers_js.GitIndexManager.acquire({ fs: fs$$1, filepath: `${gitdir}/index` }, async function (index) {
    const inode = utils_js.flatFileListToDirectoryStructure(index.entries);
    const treeRef = await constructTree({ fs: fs$$1, gitdir, inode });
    let parents;
    try {
      let parent = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref: 'HEAD' });
      parents = [parent];
    } catch (err) {
      // Probably an initial commit
      parents = [];
    }
    let comm = models_js.GitCommit.from({
      tree: treeRef,
      parent: parents,
      author: {
        name: author.name,
        email: author.email,
        timestamp: author.timestamp || Math.floor(authorDateTime.valueOf() / 1000),
        timezoneOffset: author.timezoneOffset || 0
      },
      committer: {
        name: committer.name,
        email: committer.email,
        timestamp: committer.timestamp || Math.floor(committerDateTime.valueOf() / 1000),
        timezoneOffset: committer.timezoneOffset || 0
      },
      message
    });
    if (privateKeys) {
      comm = await comm.sign(privateKeys);
    }
    oid = await managers_js.GitObjectManager.write({
      fs: fs$$1,
      gitdir,
      type: 'commit',
      object: comm.toObject()
    });
    // Update branch pointer
    const branch = await managers_js.GitRefManager.resolve({
      fs: fs$$1,
      gitdir,
      ref: 'HEAD',
      depth: 2
    });
    await fs$$1.write(path.join(gitdir, branch), oid + '\n');
  });
  return oid;
}

/**
 * List all the tracked files in a repo
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @returns {Promise<string[]>} - Resolves successfully with an array of file paths.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * let files = await listFiles(repo)
 */
async function listFiles({ gitdir, fs: _fs }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let filenames;
  await managers_js.GitIndexManager.acquire({ fs: fs$$1, filepath: `${gitdir}/index` }, async function (index) {
    filenames = index.entries.map(x => x.path);
  });
  return filenames;
}

/**
 * List all local branches
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @returns {Promise<string[]>} - Resolves successfully with an array of branch names.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * let branches = await listBranches(repo)
 */
async function listBranches({ gitdir, fs: _fs }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let files = await fs$$1.readdirDeep(`${gitdir}/refs/heads`);
  files = files.map(x => x.replace(`${gitdir}/refs/heads/`, ''));
  let text = await fs$$1.read(`${gitdir}/packed-refs`, { encoding: 'utf8' });
  if (text) {
    let refs = text.trim().split('\n').filter(x => x.includes('refs/heads')).map(x => x.replace(/^.+ refs\/heads\//, '').trim()).filter(x => !files.includes(x)); // remove duplicates
    files = files.concat(refs);
  }
  return files;
}

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

// @flow
/**
 * @typedef {Object} CommitDescription
 * @property {string} oid - SHA1 object id of this commit
 * @property {string} message - Commit message
 * @property {string} tree - SHA1 object id of corresponding file tree
 * @property {string[]} parent - an array of zero or more SHA1 oids
 * @property {Object} author
 * @property {string} author.name
 * @property {string} author.email
 * @property {number} author.timestamp - UTC Unix timestamp in seconds
 * @property {number} author.timezoneOffset - Timezone difference from UTC in minutes
 * @property {Object} committer
 * @property {string} committer.name
 * @property {string} committer.email
 * @property {number} committer.timestamp - UTC Unix timestamp in seconds
 * @property {number} committer.timezoneOffset - Timezone difference from UTC in minutes
 * @property {string} [gpgsig] - PGP signature (if present)
 */

/**
 * Get commit descriptions from the git history
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {number} [args.depth=undefined] - Limit the number of commits returned. No limit by default.
 * @param {Date} [args.since=undefined] - Return history newer than the given date. Can be combined with `depth` to get whichever is shorter.
 * @param {string} [args.ref=HEAD] - The commit to begin walking backwards through the history from.
 * @returns {Promise<CommitDescription[]>} - Resolves to an array of {@link CommitDescription} objects
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * let commits = await log(repo, {depth: 5, ref: 'master'})
 * console.log(commits)
 */
async function log({ gitdir, fs: _fs }, {
  ref = 'HEAD',
  depth,
  since // Date
}) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let sinceTimestamp = since === undefined ? undefined : Math.floor(since.valueOf() / 1000);
  // TODO: In the future, we may want to have an API where we return a
  // async iterator that emits commits.
  let commits = [];
  let start = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref });
  let { type, object } = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid: start });
  if (type !== 'commit') {
    throw new Error(`The given ref ${ref} did not resolve to a commit but to a ${type}`);
  }
  let currentCommit = _extends({ oid: start }, models_js.GitCommit.from(object).parse());
  commits.push(currentCommit);
  while (true) {
    if (depth !== undefined && commits.length === depth) break;
    if (currentCommit.parent.length === 0) break;
    let oid = currentCommit.parent[0];
    let gitobject;
    try {
      gitobject = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid });
    } catch (err) {
      commits.push({
        oid,
        error: err
      });
      break;
    }
    let { type, object } = gitobject;
    if (type !== 'commit') {
      commits.push({
        oid,
        error: new Error(`Invalid commit parent ${oid} is of type ${type}`)
      });
      break;
    }
    currentCommit = _extends({ oid }, models_js.GitCommit.from(object).parse());
    if (sinceTimestamp !== undefined && currentCommit.author.timestamp <= sinceTimestamp) {
      break;
    }
    commits.push(currentCommit);
  }
  return commits;
}

const types$1 = {
  commit: 0b0010000,
  tree: 0b0100000,
  blob: 0b0110000,
  tag: 0b1000000

  /**
   * Push a branch
   *
   * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
   * @param {Object} args - Arguments object
   * @param {integer} [args.depth=0] - Determines how much of the git repository's history to retrieve. If not specified it defaults to 0 which means the entire repo history.
   * @param {string} [args.ref=undefined] - Which branch to push. By default this is the currently checked out branch of the repository.
   * @param {string} [args.authUsername=undefined] - The username to use with Basic Auth
   * @param {string} [args.authPassword=undefined] - The password to use with Basic Auth
   * @param {string} [args.url=undefined] - The URL of the remote git server. The default is the value set in the git config for that remote.
   * @param {string} [args.remote='origin'] - If URL is not specified, determines which remote to use.
   * @returns {Promise<void>} - Resolves successfully when push completes
   *
   * @example
   * let repo = new Git({fs, dir: '.'})
   * await push(repo, {
   *   remote: 'origin',
   *   ref: 'master',
   *   authUsername: process.env.GITHUB_TOKEN,
   *   authPassword: process.env.GITHUB_TOKEN
   * })
   */
};async function push({ gitdir, fs: _fs }, { ref, remote, url, authUsername, authPassword }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  // TODO: Figure out how pushing tags works. (This only works for branches.)
  remote = remote || 'origin';
  if (url === undefined) {
    url = await config({ fs: fs$$1, gitdir }, { path: `remote.${remote}.url` });
  }
  let fullRef = ref.startsWith('refs/') ? ref : `refs/heads/${ref}`;
  let oid = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref });
  let httpRemote = new managers_js.GitRemoteHTTP(url);
  if (authUsername !== undefined && authPassword !== undefined) {
    httpRemote.auth = {
      username: authUsername,
      password: authPassword
    };
  }
  await httpRemote.preparePush();
  let commits = await listCommits({ fs: fs$$1, gitdir }, {
    start: [oid],
    finish: httpRemote.refs.values()
  });
  let objects = await listObjects({ fs: fs$$1, gitdir }, { oids: commits });
  let packstream = new stream.PassThrough();
  let oldoid = httpRemote.refs.get(fullRef) || '0000000000000000000000000000000000000000';
  packstream.write(models_js.GitPktLine.encode(`${oldoid} ${oid} ${fullRef}\0 report-status\n`));
  packstream.write(models_js.GitPktLine.flush());
  pack({ fs: fs$$1, gitdir }, {
    oids: [...objects],
    outputStream: packstream
  });
  let response = await httpRemote.push(packstream);
  return response;
}

/**
 * @ignore
 */
async function listCommits({ gitdir, fs: _fs }, { start, finish }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let startingSet = new Set();
  let finishingSet = new Set();
  for (let ref of start) {
    startingSet.add((await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref })));
  }
  for (let ref of finish) {
    // We may not have these refs locally so we must try/catch
    try {
      let oid = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref });
      finishingSet.add(oid);
    } catch (err) {}
  }
  let visited /*: Set<string> */ = new Set();

  // Because git commits are named by their hash, there is no
  // way to construct a cycle. Therefore we won't worry about
  // setting a default recursion limit.
  async function walk(oid) {
    visited.add(oid);
    let { type, object } = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid });
    if (type !== 'commit') {
      throw new Error(`Expected type commit but type is ${type}`);
    }
    let commit = models_js.GitCommit.from(object);
    let parents = commit.headers().parent;
    for (oid of parents) {
      if (!finishingSet.has(oid) && !visited.has(oid)) {
        await walk(oid);
      }
    }
  }

  // Let's go walking!
  for (let oid of startingSet) {
    await walk(oid);
  }
  return visited;
}

/**
 * @ignore
 */
async function listObjects({ gitdir, fs: _fs }, { oids /*: { oids: Set<string> } */
}) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let visited /*: Set<string> */ = new Set();

  // We don't do the purest simplest recursion, because we can
  // avoid reading Blob objects entirely since the Tree objects
  // tell us which oids are Blobs and which are Trees.
  async function walk(oid) {
    visited.add(oid);
    let { type, object } = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid });
    if (type === 'commit') {
      let commit = models_js.GitCommit.from(object);
      let tree = commit.headers().tree;
      await walk(tree);
    } else if (type === 'tree') {
      let tree = models_js.GitTree.from(object);
      for (let entry /*: TreeEntry */ of tree) {
        visited.add(entry.oid);
        // only recurse for trees
        if (entry.type === 'tree') {
          await walk(entry.oid);
        }
      }
    }
  }

  // Let's go walking!
  for (let oid of oids) {
    await walk(oid);
  }
  return visited;
}

/**
 * @ignore
 */
async function pack({ gitdir, fs: _fs }, { oids, outputStream }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let hash = crypto.createHash('sha1');
  function write(chunk, enc) {
    outputStream.write(chunk, enc);
    hash.update(chunk, enc);
  }
  function writeObject({ stype, object }) {
    let lastFour, multibyte, length;
    // Object type is encoded in bits 654
    let type = types$1[stype];
    if (type === undefined) throw new Error('Unrecognized type: ' + stype);
    // The length encoding get complicated.
    length = object.length;
    // Whether the next byte is part of the variable-length encoded number
    // is encoded in bit 7
    multibyte = length > 0b1111 ? 0b10000000 : 0b0;
    // Last four bits of length is encoded in bits 3210
    lastFour = length & 0b1111;
    // Discard those bits
    length = length >>> 4;
    // The first byte is then (1-bit multibyte?), (3-bit type), (4-bit least sig 4-bits of length)
    let byte = (multibyte | type | lastFour).toString(16);
    write(byte, 'hex');
    // Now we keep chopping away at length 7-bits at a time until its zero,
    // writing out the bytes in what amounts to little-endian order.
    while (multibyte) {
      multibyte = length > 0b01111111 ? 0b10000000 : 0b0;
      byte = multibyte | length & 0b01111111;
      write(pad(2, byte.toString(16), '0'), 'hex');
      length = length >>> 7;
    }
    // Lastly, we can compress and write the object.
    write(buffer.Buffer.from(pako.deflate(object)));
  }

  write('PACK');
  write('00000002', 'hex');
  // Write a 4 byte (32-bit) int
  write(pad(8, oids.length.toString(16), '0'), 'hex');
  for (let oid of oids) {
    let { type, object } = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid });
    writeObject({ write, object, stype: type });
  }
  // Write SHA1 checksum
  let digest = hash.digest();
  outputStream.end(digest);
  return outputStream;
}

/**
 * Remove a file from the git index (aka staging area)
 *
 * Note that this does NOT delete the file in the working directory.
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} args.filepath - The path to the file to remove to the index.
 * @returns {Promise<void>} - Resolves successfully once the git index has been updated.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * await remove(repo, {filepath: 'README.md'})
 */
async function remove({ gitdir, fs: _fs }, { filepath }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  await managers_js.GitIndexManager.acquire({ fs: fs$$1, filepath: `${gitdir}/index` }, async function (index) {
    index.delete({ filepath });
  });
  // TODO: return oid?
}

const HttpKeyServer = new openpgp_min_js.HKP();

/** @ignore */
async function verify({ gitdir, fs: _fs }, { ref, publicKeys }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  const oid = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref });
  const { type, object } = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid });
  if (type !== 'commit') {
    throw new Error(`git.verify() was expecting a ref type 'commit' but got type '${type}'`);
  }
  let commit = models_js.GitCommit.from(object);
  let author = commit.headers().author;
  let keys = await commit.listSigningKeys();
  if (!publicKeys) {
    let keyArray = await Promise.all(keys.map(id => HttpKeyServer.lookup({ keyId: id })));
    publicKeys = keyArray.join('\n');
  }
  let validity = await commit.verify(publicKeys);
  if (!validity) return false;
  return { author, keys };
}

// @flow
/*::
import type { Stats } from 'fs'
import type { CacheEntry } from '../models/GitIndex'
*/

function cacheIsStale({ entry, stats /*: {
                                     entry: CacheEntry,
                                     stats: Stats
                                     } */
}) {
  // Comparison based on the description in Paragraph 4 of
  // https://www.kernel.org/pub/software/scm/git/docs/technical/racy-git.txt
  return entry.mode !== stats.mode || entry.mtime.valueOf() !== stats.mtime.valueOf() || entry.ctime.valueOf() !== stats.ctime.valueOf() || entry.uid !== stats.uid || entry.gid !== stats.gid || entry.ino !== stats.ino >> 0 || entry.size !== stats.size;
}

async function getOidAtPath({ fs: fs$$1, gitdir, tree, path: path$$1 }) {
  if (typeof path$$1 === 'string') path$$1 = path$$1.split('/');
  let dirname = path$$1.shift();
  for (let entry of tree) {
    if (entry.path === dirname) {
      if (path$$1.length === 0) {
        return entry.oid;
      }
      let { type, object } = await managers_js.GitObjectManager.read({
        fs: fs$$1,
        gitdir,
        oid: entry.oid
      });
      if (type === 'tree') {
        let tree = models_js.GitTree.from(object);
        return getOidAtPath({ fs: fs$$1, gitdir, tree, path: path$$1 });
      }
      if (type === 'blob') {
        throw new Error(`Blob found where tree expected.`);
      }
    }
  }
  return null;
}

async function getHeadTree({ fs: fs$$1, gitdir }) {
  // Get the tree from the HEAD commit.
  let oid = await managers_js.GitRefManager.resolve({ fs: fs$$1, gitdir, ref: 'HEAD' });
  let { object: cobject } = await managers_js.GitObjectManager.read({ fs: fs$$1, gitdir, oid });
  let commit = models_js.GitCommit.from(cobject);
  let { object: tobject } = await managers_js.GitObjectManager.read({
    fs: fs$$1,
    gitdir,
    oid: commit.parseHeaders().tree
  });
  let tree = models_js.GitTree.from(tobject).entries();
  return tree;
}

/**
 * Tell whether a file has been changed
 *
 * The possible resolve values are:
 *
 * - `"ignored"` file ignored by a .gitignore rule
 * - `"unmodified"` file unchanged from HEAD commit
 * - `"*modified"` file has modifications, not yet staged
 * - `"*deleted"` file has been removed, but the removal is not yet staged
 * - `"*added"` file is untracked, not yet staged
 * - `"absent"` file not present in HEAD commit, staging area, or working dir
 * - `"modified"` file has modifications, staged
 * - `"deleted"` file has been removed, staged
 * - `"added"` previously untracked file, staged
 * - `"*unmodified"` working dir and HEAD commit match, but index differs
 * - `"*absent"` file not present in working dir or HEAD commit, but present in the index
 *
 * @param {GitRepo} repo - A {@link Git} object matching `{workdir, gitdir, fs}`
 * @param {Object} args - Arguments object
 * @param {string} args.filepath - The path to the file to query.
 * @returns {Promise<string>} - Resolves successfully with the file's git status.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * let gitstatus = await status(repo, {filepath: 'README.md'})
 * console.log(gitstatus)
 */
async function status({ workdir, gitdir, fs: _fs }, { filepath }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  let ignored = await managers_js.GitIgnoreManager.isIgnored({
    gitdir,
    workdir,
    filepath,
    fs: fs$$1
  });
  if (ignored) {
    return 'ignored';
  }
  let headTree = await getHeadTree({ fs: fs$$1, gitdir });
  let treeOid = await getOidAtPath({
    fs: fs$$1,
    gitdir,
    tree: headTree,
    path: filepath
  });
  let indexEntry = null;
  // Acquire a lock on the index
  await managers_js.GitIndexManager.acquire({ fs: fs$$1, filepath: `${gitdir}/index` }, async function (index) {
    for (let entry of index) {
      if (entry.path === filepath) {
        indexEntry = entry;
        break;
      }
    }
  });
  let stats = null;
  try {
    stats = await fs$$1._lstat(path.join(workdir, filepath));
  } catch (err) {
    if (err.code !== 'ENOENT') {
      throw err;
    }
  }

  let H = treeOid !== null; // head
  let I = indexEntry !== null; // index
  let W = stats !== null; // working dir

  const getWorkdirOid = async () => {
    if (I && !cacheIsStale({ entry: indexEntry, stats })) {
      return indexEntry.oid;
    } else {
      let object = await fs$$1.read(path.join(workdir, filepath));
      let workdirOid = await managers_js.GitObjectManager.hash({
        gitdir,
        type: 'blob',
        object
      });
      return workdirOid;
    }
  };

  if (!H && !W && !I) return 'absent'; // ---
  if (!H && !W && I) return '*absent'; // -A-
  if (!H && W && !I) return '*added'; // --A
  if (!H && W && I) {
    let workdirOid = await getWorkdirOid();
    return workdirOid === indexEntry.oid ? 'added' : '*added'; // -AA : -AB
  }
  if (H && !W && !I) return 'deleted'; // A--
  if (H && !W && I) {
    return treeOid === indexEntry.oid ? '*deleted' : '*deleted'; // AA- : AB-
  }
  if (H && W && !I) {
    let workdirOid = await getWorkdirOid();
    return workdirOid === treeOid ? '*undeleted' : '*undeletemodified'; // A-A : A-B
  }
  if (H && W && I) {
    let workdirOid = await getWorkdirOid();
    if (workdirOid === treeOid) {
      return workdirOid === indexEntry.oid ? 'unmodified' : '*unmodified'; // AAA : ABA
    } else {
      return workdirOid === indexEntry.oid ? 'modified' : '*modified'; // ABB : AAB
    }
  }
  /*
  ---
  -A-
  --A
  -AA
  -AB
  A--
  AA-
  AB-
  A-A
  A-B
  AAA
  ABA
  ABB
  AAB
  */
}

/**
 * Find the root git directory
 * @param {GitRepo} repo - A {@link Git} object matching `{fs}`
 * @param {Object} args - Arguments object
 * @param {string} args.filepath - The file directory to start searching in.
 * @returns {Promise<string>} - a directory name
 * @throws {Error} - Error('Unable to find git root')
 *
 * Starting at `filepath`, will walk upwards until it finds a directory that contains a directory called '.git'.
 *
 * @example
 * let repo = new Git({fs, dir: '.'})
 * let gitroot = await findRoot(repo, {
 *   filepath: '/path/to/some/gitrepo/path/to/some/file.txt'
 * })
 * // gitroot = '/path/to/some/gitrepo'
 */
async function findRoot({ fs: _fs }, { filepath }) {
  const fs$$1 = new models_js.FileSystem(_fs);
  return _findRoot(fs$$1, filepath);
}

async function _findRoot(fs$$1, filepath) {
  if (await fs$$1.exists(path.join(filepath, '.git'))) {
    return filepath;
  } else {
    let parent = path.dirname(filepath);
    if (parent === filepath) throw new Error('Unable to find git root');
    return _findRoot(fs$$1, parent);
  }
}

var version$1 = "0.0.0-development";

/**
 * Return the version number of 'isomorphic-git'
 *
 * I don't know why you might need this. I added it just so I could check that I was getting
 * the correct version of the library and not a cached version.
 * @returns {string} version - the version string taken from package.json at publication time
 * @example
 * console.log(version())
 */
function version() {
  return version$1;
}

/**
 * @external {FSModule} http://ghub.io/browserfs
 */

/**
 * @typedef {Object} GitRepo
 * @property {FSModule} fs
 * @property {string} workdir
 * @property {string} gitdir
 */

/**
 *
 * The "state" of a git repo is pretty darn simple. It consists of three things:
 *
 * - `fs` - the filesystem the repo lives in
 * - `workdir` - the directory path where files are checked out
 * - `gitdir` - the directory path where the git object database lives
 *
 * However most of the time, the relationship between `workdir` and `gitdir` is simply `gitdir = path.join(workdir, '.git')`.
 * So as a shorthand, you can use the `Git` constructor with `{fs, dir}`.
 *
 * If you are working with bare repositories, that relationship between the gitdir and workdir does not hold.
 * In this case, you need to specify the directories explicitly.
 *
 * @implements {GitRepo}
 * @prop {string} gitdir
 * @prop {string} workdir
 *
 * @example
 * import fs from 'fs'
 * import { Git } from 'isomorphic-git'
 * // shorthand
 * let repo = new Git({fs, dir: './path/to/repo'})
 * // second way
 * let repo2 = new Git({fs, gitdir: './my-bare-repo', workdir: '/var/www/website'})
 */
class Git {
  /**
   * @constructor
   * @param {Object} args
   * @param {FSModule} args.fs - The filesystem holding the git repo
   * @param {string} args.dir
   * @param {string} [args.gitdir=dir]
   * @param {string} [args.workdir=path.join(dir, '.git')]
   */
  constructor({ fs: fs$$1, dir, workdir, gitdir }) {
    if (fs$$1) {
      /**
       * @type {FSModule}
       */
      this.fs = fs$$1;
      utils_js.setfs(fs$$1);
    }
    if (dir) {
      /**
       * The directory where your files are checked out.
       * Usually this is the parent directory of ".git" but it doesn't have to be.
       *
       * @type {string}
       */
      this.workdir = dir;
      /**
       * The directory where your git repository history is stored.
       * Usually this is a directory called ".git" inside your working directory.
       *
       * @type {string}
       */
      this.gitdir = path.join(dir, '.git');
    }
    if (workdir) this.workdir = workdir;
    if (gitdir) this.gitdir = gitdir;
    if (!this.fs) {
      throw new Error("Missing required argument 'fs' in Git constructor.");
    }
    if (!this.gitdir) {
      throw new Error("Missing required argument 'gitdir' in Git constructor.");
    }
  }
  /**
   * @returns {string} - The version of `isomorphic-git` (taken from `package.json` at publish time)
   */
  static version() {
    return utils_js.pkg.version;
  }
}

exports.add = add;
exports.clone = clone;
exports.checkout = checkout;
exports.commit = commit;
exports.fetch = fetch;
exports.init = init;
exports.listFiles = listFiles;
exports.listBranches = listBranches;
exports.log = log;
exports.push = push;
exports.remove = remove;
exports.config = config;
exports.verify = verify;
exports.status = status;
exports.findRoot = findRoot;
exports.version = version;
exports.Git = Git;
