recordUpload function

UploadRecordResult recordUpload(
  1. Git git,
  2. UploadRecord record, {
  3. bool push = true,
  4. bool dryRun = false,
  5. bool failedPushIsFatal = true,
})

Records that record reached a store, and pushes it.

Idempotent for a repeated upload of the same artifact, and a hard error when the same name already names a different commit.

"The tag exists" is not idempotence, and the distinction is the whole point of this function. git tag refuses an existing name whether it points at the same commit or a different one, so a caller that treats refusal as success will publish one artifact while the record names another. Where a build number can be allocated twice — concurrent CI on different commits, or a forced number — that is precisely how it happens.

push is for tests, and an upload path must never pass false. The push is not bookkeeping here — it is the only guard that sees a collision raised on another machine. Locally this function can compare against a tag this clone happens to have; the concurrent-CI case it exists for is precisely the one where the other allocation is on a different runner, and the only way this process learns of it is the remote rejecting the push. Passing false to save a network round trip keeps every local check and silently forfeits the cross-machine one, with nothing to indicate the guarantee is gone.

failedPushIsFatal is the one thing that differs between a record written before its event and one written after it, and the comment on the push below already named the distinction before anything needed it: elsewhere a failed tag push is a warning because the release has already gone out and the tag is bookkeeping; here nothing has gone out yet. An upload record is written before the store is contacted, so a push that fails means the upload must not proceed, and the default stays true. A promotion record is written after a person has already pressed the button in a console — failing the run there does not un-promote anything, it only costs the operator the step they just did, and the next run stops at the same console asking them to do it again. Such a caller passes false and gets UploadRecordResult.writtenNotPushed to report.

It does not soften a collision. A remote tag naming a different commit is a disagreement about what happened rather than a failure to transmit, and that throws whichever side of its event the record sits on.

That sentence rests entirely on remoteTag being able to see origin's tag, and it was false for a while because that function could not see a lightweight one. Worth naming here rather than only there: this path has no other way to tell a collision from a failure to transmit, so anything that query cannot answer is silently the tolerable case.

Which is also why a lightweight tag on origin at the right commit is refused rather than accepted as a record. Seeing it was the fix; believing it would have been half of one.

Implementation

UploadRecordResult recordUpload(
  Git git,
  UploadRecord record, {
  bool push = true,
  bool dryRun = false,
  bool failedPushIsFatal = true,
}) {
  // "The whole tag name" means the name, not the ref path — and the difference
  // is invisible without this, because every use here is consistent. `git tag`
  // would create `refs/tags/refs/tags/…`, lookups would find it, pushes would
  // publish it, and the run would be green while the record sat under a name
  // nobody will ever look up.
  if (record.name.startsWith('refs/')) {
    throw ReleaseException(
      'Tag name "${record.name}" starts with refs/, which git would nest '
      'under refs/tags/ rather than treat as a path. Pass the name only.',
    );
  }

  final commit = resolveCommit(git, record.commit);
  final existing = taggedCommit(git, record.name);

  if (existing != null && existing != commit) {
    throw UploadCollisionException(
      'Tag ${record.name} already names a different commit.\n'
      '  it points at:   $existing\n'
      '  this artifact:  $commit\n'
      'One build number has been used for two commits, so publishing this '
      'would leave the record naming the wrong one. Nothing was uploaded.',
    );
  }

  if (existing != null && !_isAnnotated(git, record.name)) {
    throw ReleaseException(
      'Tag ${record.name} exists at the right commit but is lightweight, so '
      'it carries no annotation — the build number, the checksum and which '
      'store took it are all absent, and treating it as the record would put '
      'an empty one in the repository. This tool only writes annotated tags, '
      'so something else created it. Delete it and re-run, or annotate it by '
      'hand. Nothing was uploaded.',
    );
  }

  final result = existing == null
      ? UploadRecordResult.created
      : UploadRecordResult.alreadyRecorded;

  if (dryRun) {
    return result;
  }

  if (existing == null) {
    // **`--cleanup=whitespace`, because the default deletes lines.** `git tag`
    // cleans a message given with `-m` exactly as it cleans one typed in an
    // editor, and its default mode drops every line starting with `#` as a
    // comment. The annotation is the record, and a caller's line may well
    // start that way: a promotion refused with the reason "#418 is why the
    // console said no" came out as a refusal with no reason at all, the tag
    // written and pushed and nothing red (found in review of the promotion
    // writer, before it shipped). This mode still trims blank lines and leaves
    // the rest alone.
    git.run([
      'tag',
      '-a',
      '--cleanup=whitespace',
      record.name,
      commit,
      '-m',
      record.annotation,
    ]);
  }

  if (push) {
    // **Pushed on both paths, not only the one that created the tag.** A local
    // tag is not a record — the machine that will read it is the next CI job,
    // and that one clones. So the run whose push failed must be repairable by
    // the retry, and it is not if the retry sees a local tag, calls that
    // `alreadyRecorded` and returns without pushing: the artifact then uploads
    // against a record that exists nowhere but the machine that has since been
    // torn down. A retried job after a network failure is the ordinary case,
    // not the exotic one.
    //
    // **A rejected push does not mean a collision, and assuming it did broke
    // every parallel release.** The sentence that used to be here said pushing
    // a tag the remote already holds at this commit is a no-op. That is true
    // for lightweight tags and for byte-identical objects, and false for the
    // case that actually happens: two CI jobs sharing a commit and a build
    // number each mint their *own* annotated tag object — different timestamp,
    // different message — and git refuses to replace one with the other. The
    // rejection reads `! [rejected] ... (already exists)`, which is the same
    // words as the collision it is not.
    //
    // So the remote is asked what its tag actually names, exactly as the local
    // path asks above.
    //
    // Deliberately not `allowFailure` beyond this. Elsewhere a failed tag push
    // is a warning because the release has already gone out and the tag is
    // bookkeeping; here nothing has gone out yet, and an unpushed tag protects
    // nothing.
    final pushed = git.ok(['push', 'origin', 'refs/tags/${record.name}']);
    if (!pushed) {
      final remote = remoteTag(git, record.name);
      if (remote == null) {
        // Rejected, and origin does not hold this tag — so the push failed for
        // some other reason (credentials, network, a hook).
        //
        // **The retry happens on both paths, because it is the reason this
        // branch exists** rather than a side effect of wanting git's message:
        // a transient failure that succeeds on the second attempt is the
        // ordinary case here. What differs is only what a second failure
        // means. Fatal: re-run without `ok`, so the exception carries git's own
        // words rather than ones invented here. Not fatal: the tag is local and
        // the caller is told so, which is the whole of what it can act on —
        // git's message is lost on this path, and that is the cost of the run
        // continuing.
        if (!failedPushIsFatal) {
          final retried = git.ok([
            'push',
            'origin',
            'refs/tags/${record.name}',
          ]);
          return retried ? result : UploadRecordResult.writtenNotPushed;
        }
        git.run(['push', 'origin', 'refs/tags/${record.name}']);
        // **And return, because the retry may have worked.** Falling through
        // with `remote` still null compared null against the commit and threw
        // a collision reading `origin points at: null` — exit 3, the code
        // wrappers are documented to treat as unrecoverable — for a push that
        // had just landed. A transient failure that succeeds on the second
        // attempt is the ordinary reason to reach this branch.
        return result;
      }
      if (remote.commit != commit) {
        throw UploadCollisionException(
          'Tag ${record.name} already names a different commit on origin.\n'
          '  origin points at:  ${remote.commit}\n'
          '  this artifact:     $commit\n'
          'One build number has been used for two commits, so publishing this '
          'would leave the record naming the wrong one. Nothing was uploaded.',
        );
      }
      if (!remote.annotated) {
        // **The same refusal as the local one above, applied to origin.**
        // Right commit, no annotation: the build number, the checksum and
        // which store took it are all absent, and this run's annotated tag was
        // rejected rather than replacing it — so returning `alreadyRecorded`
        // would report a record that exists nowhere but as a bare ref on
        // origin, while the real one stayed on a machine about to be torn
        // down. For a `promoted/` refusal that annotation is the operator's
        // reason, which is the only thing a refusal record carries at all.
        //
        // Accepting it here while refusing it locally would have made the same
        // tag a record or an empty one depending only on which clone found it
        // first.
        throw ReleaseException(
          'Tag ${record.name} exists on origin at the right commit but is '
          'lightweight, so it carries no annotation — and the annotation is '
          'the record. This run wrote an annotated tag and origin refused to '
          'take it, so the record would exist only on this machine. This tool '
          'only writes annotated tags, so something else created that one: '
          'delete it on origin and re-run, or annotate it by hand. Nothing '
          'was uploaded.',
        );
      }
      // Same commit, someone else's tag object. Another job recorded this exact
      // build first, which is the ordinary outcome of a release matrix rather
      // than an error: the record exists, on origin, naming the right commit.
      return UploadRecordResult.alreadyRecorded;
    }
  }

  return result;
}