pcottle/learnGitBranching · error · GitError

cannot fetch to ' + ref + ' when checked out on ' + ref

Error message

cannot fetch to ' + ref + ' when checked out on ' + ref

What it means

assertNotCheckedOut throws when a fetch/push-like command would write to a remote-tracking ref that corresponds to the branch currently checked out (engine.HEAD points at it). Mirrors git's refusal to update the branch you're on via fetch.

Solutions

  1. git checkout another branch first, then fetch into the ref
  2. Fetch without a destination refspec (just git fetch origin) and let o/ tracking refs update
  3. Push instead of fetch if your intent was to update origin

Example fix

// before
git checkout maingit fetch origin main:main
// after
git checkout -b tempgit fetch origin main:main
Defensive patterns

Strategy: validation

Validate before calling

function canFetchInto(engine, ref) { return !!engine.refs[ref] && engine.HEAD.get('target') !== engine.refs[ref]; }

Try / catch

try { fetchInto(ref); } catch (e) { if (e instanceof GitError && /checked out/.test(e.msg)) checkoutTempThenRetry(); else throw e; }

Prevention

When it happens

Trigger: Fetching into a ref (e.g. git fetch origin main:main) while HEAD targets that same branch/ref in the simulated engine.

Common situations: Practicing refspec fetches in LearnGitBranching remote levels; forgetting to switch branches before simulating a fetch-to-ref.

Related errors


AI-assisted analysis of pcottle/learnGitBranching@5b09d0ff96 (2026-08-27). Data as JSON: /api/errors/bf7c531bcc98b87b. Report an issue: GitHub.

Appendix: source

Thrown at src/js/git/commands.js:53

};

var validateOriginBranchName = function(engine, name) {
  return engine.origin.validateBranchName(name);
};

var validateBranchNameIfNeeded = function(engine, name) {
  if (engine.refs[name]) {
    return name;
  }
  return validateBranchName(engine, name);
};

var assertNotCheckedOut = function(engine, ref) {
  if (!engine.refs[ref]) {
    return;
  }
  if (engine.HEAD.get('target') === engine.refs[ref]) {
    throw new GitError({
      msg: intl.todo(
        'cannot fetch to ' + ref + ' when checked out on ' + ref
      )
    });
  }
};

var assertIsBranch = function(engine, ref) {
  assertIsRef(engine, ref);
  var obj = engine.resolveID(ref);
  if (!obj || obj.get('type') !== 'branch') {
    throw new GitError({
      msg: intl.todo(
        ref + ' is not a branch'
      )
    });
  }
};

View on GitHub (pinned to 5b09d0ff96)