Patchwork D783: util: add safename function for generating safe names to rename to

login
register
mail settings
Submitter phabricator
Date Oct. 10, 2017, 1:36 a.m.
Message ID <e6481057e639ad737546df21ecf41e38@localhost.localdomain>
Download mbox | patch
Permalink /patch/24695/
State Not Applicable
Headers show

Comments

phabricator - Oct. 10, 2017, 1:36 a.m.
This revision was automatically updated to reflect the committed changes.
Closed by commit rHGb8b2804ba00d: util: add safename function for generating safe names to rename to (authored by mbthomas, committed by ).

REPOSITORY
  rHG Mercurial

CHANGES SINCE LAST UPDATE
  https://phab.mercurial-scm.org/D783?vs=2360&id=2554

REVISION DETAIL
  https://phab.mercurial-scm.org/D783

AFFECTED FILES
  mercurial/util.py

CHANGE DETAILS




To: mbthomas, #hg-reviewers, ryanmce
Cc: ryanmce, mercurial-devel

Patch

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -26,6 +26,7 @@ 
 import gc
 import hashlib
 import imp
+import itertools
 import mmap
 import os
 import platform as pyplatform
@@ -3835,3 +3836,26 @@ 
 
 # convenient shortcut
 dst = debugstacktrace
+
+def safename(f, tag, ctx, others=None):
+    """
+    Generate a name that it is safe to rename f to in the given context.
+
+    f:      filename to rename
+    tag:    a string tag that will be included in the new name
+    ctx:    a context, in which the new name must not exist
+    others: a set of other filenames that the new name must not be in
+
+    Returns a file name of the form oldname~tag[~number] which does not exist
+    in the provided context and is not in the set of other names.
+    """
+    if others is None:
+        others = set()
+
+    fn = '%s~%s' % (f, tag)
+    if fn not in ctx and fn not in others:
+        return fn
+    for n in itertools.count(1):
+        fn = '%s~%s~%s' % (f, tag, n)
+        if fn not in ctx and fn not in others:
+            return fn