{"size": 1099, "ext": "js", "max_stars_repo_path": "src/commands/currentBranch.js", "max_stars_repo_name": "mizchi/isomorphic-git", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/commands/currentBranch.js", "max_issues_repo_name": "mizchi/isomorphic-git", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/commands/currentBranch.js", "max_forks_repo_name": "mizchi/isomorphic-git", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.5490196078, "max_line_length": 73, "alphanum_fraction": 0.6214740673}
import path from 'path'

import { GitRefManager } from '../managers/GitRefManager.js'
import { FileSystem } from '../models/FileSystem.js'

// @see https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions
const regexs = [
  new RegExp('refs/remotes/(.*)/HEAD'),
  new RegExp('refs/remotes/(.*)'),
  new RegExp('refs/heads/(.*)'),
  new RegExp('refs/tags/(.*)'),
  new RegExp('refs/(.*)')
]

function abbreviate (ref) {
  for (const reg of regexs) {
    let matches = reg.exec(ref)
    if (matches) {
      return matches[1]
    }
  }
  return ref
}

/**
 * Get the name of the branch currently pointed to by .git/HEAD
 *
 * @link https://isomorphic-git.github.io/docs/currentBranch.html
 */
export async function currentBranch ({
  dir,
  gitdir = path.join(dir, '.git'),
  fs: _fs,
  fullname = false
}) {
  try {
    const fs = new FileSystem(_fs)
    let ref = await GitRefManager.resolve({
      fs,
      gitdir,
      ref: 'HEAD',
      depth: 2
    })
    if (fullname) return ref
    return abbreviate(ref)
  } catch (err) {
    err.caller = 'git.currentBranch'
    throw err
  }
}
