check if a specific revision of a doc has been deleted - metadata: the metadata object from the doc store - rev: (optional) the revision to check. defaults to winning revision
966651
function isDeleted(metadata, rev) {
  if (!rev) {
    rev = winningRev(metadata);
  }
  var id = rev.substring(rev.indexOf('-') + 1);
  var toVisit = metadata.rev_tree.map(getTrees);

  var tree;
  while ((tree = toVisit.pop())) {
    if (tree[0] === id) {
      return !!tree[1].deleted;
    }
    toVisit = toVisit.concat(tree[2]);
  }
}
210203
function(revision)
  {
    if ( isFunction( revision ) )
    {
      this.revisionFunction = revision;
    }
    else if ( isString( revision ) )
    {
      this.revisionFunction = function(a, b)
      {
        var ar = isObject( a ) && revision in a ? a[ revision ] : undefined;
        var br = isObject( b ) && revision in b ? b[ revision ] : undefined;

        return ar === undefined || br === undefined ? false : compare( ar, br ) > 0;
      };
    }
    else
    {
      this.revisionFunction = function(a, b)
      {
        return false;
      };
    }
  }
273974
def _metadata_is_invalid(cls, fact):
        
        return any(isinstance(token, URIRef) and ' ' in token
                   for token in fact)
717997
def _get_revision(self, revision):
        

        is_null = lambda o: len(o) == revision.count('0')

        try:
            self.revisions[0]
        except (KeyError, IndexError):
            raise EmptyRepositoryError("There are no changesets yet")

        if revision in (None, '', 'tip', 'HEAD', 'head', -1):
            return self.revisions[-1]

        is_bstr = isinstance(revision, (str, unicode))
        if ((is_bstr and revision.isdigit() and len(revision) < 12)
            or isinstance(revision, int) or is_null(revision)):
            try:
                revision = self.revisions[int(revision)]
            except Exception:
                raise ChangesetDoesNotExistError("Revision %s does not exist "
                    "for this repository" % (revision))

        elif is_bstr:
            # get by branch/tag name
            _ref_revision = self._parsed_refs.get(revision)
            if _ref_revision:  # and _ref_revision[1] in ['H', 'RH', 'T']:
                return _ref_revision[0]

            _tags_shas = self.tags.values()
            # maybe it's a tag ? we don't have them in self.revisions
            if revision in _tags_shas:
                return _tags_shas[_tags_shas.index(revision)]

            elif not SHA_PATTERN.match(revision) or revision not in self.revisions:
                raise ChangesetDoesNotExistError("Revision %s does not exist "
                    "for this repository" % (revision))

        # Ensure we return full id
        if not SHA_PATTERN.match(str(revision)):
            raise ChangesetDoesNotExistError("Given revision %s not recognized"
                % revision)
        return revision
110629
def _get_revision(self, revision):
        

        if self._empty:
            raise EmptyRepositoryError("There are no changesets yet")

        if revision in [-1, 'tip', None]:
            revision = 'tip'

        try:
            revision = hex(self._repo.lookup(revision))
        except (IndexError, ValueError, RepoLookupError, TypeError):
            raise ChangesetDoesNotExistError("Revision %s does not "
                                    "exist for this repository"
                                    % (revision))
        return revision
911221
@InterfaceAudience.Private
    protected void revisionAdded(DocumentChange change, boolean notify) {
        if (change.getRevisionId() != null) {
            String revID = change.getWinningRevisionID();
            if (revID == null)
                return;  // current revision didn't change

            if (currentRevision != null && !revID.equals(currentRevision.getId())) {
                RevisionInternal rev = change.getWinningRevisionIfKnown();
                if (rev == null)
                    forgetCurrentRevision();
                else if (rev.isDeleted())
                    currentRevision = null;
                else
                    currentRevision = new SavedRevision(this, rev);
            }
        } else {
            // Document was purged!
            currentRevision = null;
        }

        if (notify) {
            for (ChangeListener listener : changeListeners)
                listener.changed(new ChangeEvent(this, change));
        }
    }

    @InterfaceAudience.Private
    protected void forgetCurrentRevision() {
        currentRevision = null;
    }
}
489409
def document_changes(document)
      (document.changed + document._children.select{|child| child.changed? }.map { |child|
        "#{child.metadata_name.to_s}{#{child.changed.join(", ")}}"
      }).join(", ")
    end
387818
def revision(self):
        """"""
        location, _, revision = self.expression.partition('#')
        return revision if location and revision else self.expression
210346
def modified?(doc)
      return true if metadata[doc.path]&.[](:forced)
      return true unless File.exist?(site.in_dest_dir(doc.path))
      modified, hash = file_mtime_of(doc.path), metadata[doc.path]
      return modified > hash[:last_modified] if hash && !hash[:dynamic] && hash[:seen_before]
      return hash[:seen_before] = true if hash && !hash[:seen_before]
      return dependencies_modified?(hash) if hash
      add(doc.path).update(seen_before: true)

      true
    end
1135717
@InterfaceAudience.Private
    public void pullRemoteRevision(final RevisionInternal rev) {

        Log.d(TAG, "%s: pullRemoteRevision with rev: %s", this, rev);

        ++httpConnectionCount;

        // Construct a query. We want the revision history, and the bodies of attachments that have
        // been added since the latest revisions we have locally.
        // See: http://wiki.apache.org/couchdb/HTTP_Document_API#Getting_Attachments_With_a_Document
        StringBuilder path = new StringBuilder(encodeDocumentId(rev.getDocID()));
        path.append("?rev=").append(URIUtils.encode(rev.getRevID()));
        path.append("&revs=true");

        // TODO: CBL Java does not have implementation of _settings yet. Till then, attachments always true
        boolean attachments = true;
        if (attachments)
            path.append("&attachments=true");

        // Include atts_since with a list of possible ancestor revisions of rev. If getting attachments,
        // this allows the server to skip the bodies of attachments that have not changed since the
        // local ancestor. The server can also trim the revision history it returns, to not extend past
        // the local ancestor (not implemented yet in SG but will be soon.)
        AtomicBoolean haveBodies = new AtomicBoolean(false);
        List<String> possibleAncestors = null;
        possibleAncestors = db.getPossibleAncestorRevisionIDs(rev,
                PullerInternal.MAX_NUMBER_OF_ATTS_SINCE, attachments ? haveBodies : null, true);
        if (possibleAncestors != null) {
            path.append(haveBodies.get() ? "&atts_since=" : "&revs_from=");
            path.append(joinQuotedEscaped(possibleAncestors));
        } else {
            int maxRevTreeDepth = getLocalDatabase().getMaxRevTreeDepth();
            if (rev.getGeneration() > maxRevTreeDepth) {
                path.append("&revs_limit=");
                path.append(maxRevTreeDepth);
            }
        }

        //create a final version of this variable for the log statement inside
        //FIXME find a way to avoid this
        final String pathInside = path.toString();
        CustomFuture future = sendAsyncMultipartDownloaderRequest("GET", pathInside,
                null, db, new RemoteRequestCompletion() {

                    @Override
                    public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
                        if (e != null) {
                            Log.w(TAG, "Error pulling remote revision: %s", e, this);
                            if (Utils.isDocumentError(e)) {
                                // Revision is missing or not accessible:
                                revisionFailed(rev, e);
                            } else {
                                // Request failed:
                                setError(e);
                            }
                        } else {

                            Map<String, Object> properties = (Map<String, Object>) result;
                            long size = 0;
                            if (httpResponse != null && httpResponse.body() != null)
                                size = httpResponse.body().contentLength();
                            PulledRevision gotRev = new PulledRevision(properties, size);
                            gotRev.setSequence(rev.getSequence());

                            Log.d(TAG, "%s: pullRemoteRevision add rev: %s to batcher: %s",
                                    PullerInternal.this, gotRev, downloadsToInsert);

                            // NOTE: should not/not necessary to call Body.compact()
                            // new PulledRevision(Map<string, Object>) creates Body instance only
                            // with `object`. Serializing object to json causes two unnecessary
                            // JSON serializations.

                            if (gotRev.getBody() != null)
                                queuedMemorySize.addAndGet(gotRev.getBody().getSize());

                            // Add to batcher ... eventually it will be fed to -insertRevisions:.
                            downloadsToInsert.queueObject(gotRev);

                            // if queue memory size is more than maximum, force flush the queue.
                            if (queuedMemorySize.get() > MAX_QUEUE_MEMORY_SIZE) {
                                Log.d(TAG, "Flushing  queued memory size at: " + queuedMemorySize);
                                downloadsToInsert.flushAllAndWait();
                            }
                        }

                        // Note that we've finished this task:
                        --httpConnectionCount;

                        // Start another task if there are still revisions waiting to be pulled:
                        pullRemoteRevisions();
                    }
                });
        future.setQueue(pendingFutures);
        pendingFutures.add(future);
    }
1367170
def _doc_rev(self, res):
        
        jstr = res.headers['X-Couchbase-Meta']
        jobj = json.loads(jstr)
        return jobj['rev']
254396
def _check_rev_dict(tree, ebt):
    """"""
    ebs = defaultdict(dict)
    for edge in ebt.values():
        source_id = edge['@source']
        edge_id = edge['@id']
        ebs[source_id][edge_id] = edge
    assert ebs == tree['edgeBySourceId']
279342
def list_revisions(path)
      resp = request('/files/list_revisions', path: path)
      entries = resp['entries'].map { |e| FileMetadata.new(e) }
      return entries, resp['is_deleted']
    end
1312935
function(doc, callback) {
        audit([doc], 'delete', function(err) {
          if (err) {
            return callback(err);
          }
          docsDb.removeDoc(doc._id, doc._rev, callback);
        });
      }
792756
def metadata(self, key=None, database=None, table=None, fallback=True):
        
        assert not (database is None and table is not None), \
            "Cannot call metadata() with table= specified but not database="
        databases = self._metadata.get("databases") or {}
        search_list = []
        if database is not None:
            search_list.append(databases.get(database) or {})
        if table is not None:
            table_metadata = (
                (databases.get(database) or {}).get("tables") or {}
            ).get(table) or {}
            search_list.insert(0, table_metadata)
        search_list.append(self._metadata)
        if not fallback:
            # No fallback allowed, so just use the first one in the list
            search_list = search_list[:1]
        if key is not None:
            for item in search_list:
                if key in item:
                    return item[key]
            return None
        else:
            # Return the merged list
            m = {}
            for item in search_list:
                m.update(item)
            return m
19853
def update_metadata_from_rmd_options(name, value, metadata):
    
    for jupyter_option, rmd_option, rev in _BOOLEAN_OPTIONS_DICTIONARY:
        if name == rmd_option:
            try:
                metadata[jupyter_option] = _py_logical_values(value) != rev
                return True
            except RLogicalValueError:
                pass
    return False
552867
function RevisionGuard (store, options) {
  options = options || {};

  var defaults = {
    queueTimeout: 1000,
    queueTimeoutMaxLoops: 3//,
    // startRevisionNumber: 1
  };

  _.defaults(options, defaults);

  this.options = options;

  if (!store || !_.isObject(store)) {
    var err = new Error('store not injected!');
    debug(err);
    throw err;
  }

  this.store = store;

  this.definition = {
    correlationId: 'correlationId', // optional
    id: 'id',                       // optional
    name: 'name',                   // optional
//    aggregateId: 'aggregate.id',    // optional
//    context: 'context.name',        // optional
//    aggregate: 'aggregate.name',    // optional
    payload: 'payload'              // optional
//    revision: 'revision'            // optional
//    version: 'version',             // optional
//    meta: 'meta'                    // optional, if defined theses values will be copied to the notification (can be used to transport information like userId, etc..)
  };

  this.queue = new Queue({ queueTimeout: this.options.queueTimeout });

  this.currentHandlingRevisions = {};

  this.onEventMissing(function (info, evt) {
    debug('missing events: ', info, evt);
  });
}