]> arthur.barton.de Git - bup.git/blobdiff - lib/bup/helpers.py
import-duplicity: use readpipe, not check_output
[bup.git] / lib / bup / helpers.py
index 811a8f1f3017f34d2555e083bf00ee123a44743c..385647ec1b8f1d90e2b5ccba7f69c38626a4e55e 100644 (file)
@@ -13,8 +13,8 @@ sc_page_size = os.sysconf('SC_PAGE_SIZE')
 assert(sc_page_size > 0)
 
 sc_arg_max = os.sysconf('SC_ARG_MAX')
-if sc_arg_max == -1:
-    sc_arg_max = 4096
+if sc_arg_max == -1:  # "no definite limit" - let's choose 2M
+    sc_arg_max = 2 * 1024 * 1024
 
 # This function should really be in helpers, not in bup.options.  But we
 # want options.py to be standalone so people can include it in other projects.
@@ -41,11 +41,25 @@ def atof(s):
 buglvl = atoi(os.environ.get('BUP_DEBUG', 0))
 
 
-# If the platform doesn't have fdatasync (OS X), fall back to fsync.
 try:
-    fdatasync = os.fdatasync
+    _fdatasync = os.fdatasync
 except AttributeError:
-    fdatasync = os.fsync
+    _fdatasync = os.fsync
+
+if sys.platform.startswith('darwin'):
+    # Apparently os.fsync on OS X doesn't guarantee to sync all the way down
+    import fcntl
+    def fdatasync(fd):
+        try:
+            return fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
+        except IOError as e:
+            # Fallback for file systems (SMB) that do not support F_FULLFSYNC
+            if e.errno == errno.ENOTSUP:
+                return _fdatasync(fd)
+            else:
+                raise
+else:
+    fdatasync = _fdatasync
 
 
 # Write (blockingly) to sockets that may or may not be in blocking mode.
@@ -59,7 +73,7 @@ def _hard_write(fd, buf):
             raise IOError('select(fd) returned without being writable')
         try:
             sz = os.write(fd, buf)
-        except OSError, e:
+        except OSError as e:
             if e.errno != errno.EAGAIN:
                 raise
         assert(sz >= 0)
@@ -129,7 +143,7 @@ def mkdirp(d, mode=None):
             os.makedirs(d, mode)
         else:
             os.makedirs(d)
-    except OSError, e:
+    except OSError as e:
         if e.errno == errno.EEXIST:
             pass
         else:
@@ -193,14 +207,15 @@ def unlink(f):
     """
     try:
         os.unlink(f)
-    except OSError, e:
+    except OSError as e:
         if e.errno != errno.ENOENT:
             raise
 
 
-def readpipe(argv, preexec_fn=None):
+def readpipe(argv, preexec_fn=None, shell=False):
     """Run a subprocess and return its output."""
-    p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn=preexec_fn)
+    p = subprocess.Popen(argv, stdout=subprocess.PIPE, preexec_fn=preexec_fn,
+                         shell=shell)
     out, err = p.communicate()
     if p.returncode != 0:
         raise Exception('subprocess %r failed with status %d'
@@ -243,8 +258,8 @@ to return multiple strings in order to respect ARG_MAX)."""
         yield readpipe(command + sub_args, preexec_fn=preexec_fn)
 
 
-def realpath(p):
-    """Get the absolute path of a file.
+def resolve_parent(p):
+    """Return the absolute path of a file without following any final symlink.
 
     Behaves like os.path.realpath, but doesn't follow a symlink for the last
     element. (ie. if 'p' itself is a symlink, this one won't follow it, but it
@@ -735,7 +750,8 @@ if _mincore:
 
     def fmincore(fd):
         """Return the mincore() data for fd as a bytearray whose values can be
-        tested via MINCORE_INCORE"""
+        tested via MINCORE_INCORE, or None if fd does not fully
+        support the operation."""
         st = os.fstat(fd)
         if (st.st_size == 0):
             return bytearray(0)
@@ -750,7 +766,13 @@ if _mincore:
         for ci in xrange(chunk_count):
             pos = _fmincore_chunk_size * ci;
             msize = min(_fmincore_chunk_size, st.st_size - pos)
-            m = mmap.mmap(fd, msize, mmap.MAP_PRIVATE, 0, 0, pos)
+            try:
+                m = mmap.mmap(fd, msize, mmap.MAP_PRIVATE, 0, 0, pos)
+            except mmap.error as ex:
+                if ex.errno == errno.EINVAL or ex.errno == errno.ENODEV:
+                    # Perhaps the file was a pipe, i.e. "... | bup split ..."
+                    return None
+                raise ex
             _mincore(m, msize, 0, result, ci * pages_per_chunk);
         return result
 
@@ -871,7 +893,7 @@ def parse_date_or_fatal(str, fatal):
     For now we expect a string that contains a float."""
     try:
         date = float(str)
-    except ValueError, e:
+    except ValueError as e:
         raise fatal('invalid date format (should be a float): %r' % e)
     else:
         return date
@@ -884,15 +906,15 @@ def parse_excludes(options, fatal):
     for flag in options:
         (option, parameter) = flag
         if option == '--exclude':
-            excluded_paths.append(realpath(parameter))
+            excluded_paths.append(resolve_parent(parameter))
         elif option == '--exclude-from':
             try:
-                f = open(realpath(parameter))
-            except IOError, e:
+                f = open(resolve_parent(parameter))
+            except IOError as e:
                 raise fatal("couldn't read %s" % parameter)
             for exclude_path in f.readlines():
                 # FIXME: perhaps this should be rstrip('\n')
-                exclude_path = realpath(exclude_path.strip())
+                exclude_path = resolve_parent(exclude_path.strip())
                 if exclude_path:
                     excluded_paths.append(exclude_path)
     return sorted(frozenset(excluded_paths))
@@ -908,12 +930,12 @@ def parse_rx_excludes(options, fatal):
         if option == '--exclude-rx':
             try:
                 excluded_patterns.append(re.compile(parameter))
-            except re.error, ex:
+            except re.error as ex:
                 fatal('invalid --exclude-rx pattern (%s): %s' % (parameter, ex))
         elif option == '--exclude-rx-from':
             try:
-                f = open(realpath(parameter))
-            except IOError, e:
+                f = open(resolve_parent(parameter))
+            except IOError as e:
                 raise fatal("couldn't read %s" % parameter)
             for pattern in f.readlines():
                 spattern = pattern.rstrip('\n')
@@ -921,7 +943,7 @@ def parse_rx_excludes(options, fatal):
                     continue
                 try:
                     excluded_patterns.append(re.compile(spattern))
-                except re.error, ex:
+                except re.error as ex:
                     fatal('invalid --exclude-rx pattern (%s): %s' % (spattern, ex))
     return excluded_patterns
 
@@ -1049,10 +1071,15 @@ if _localtime:
     def localtime(time):
         return bup_time(*_helpers.localtime(time))
     def utc_offset_str(t):
-        'Return the local offset from UTC as "+hhmm" or "-hhmm" for time t.'
+        """Return the local offset from UTC as "+hhmm" or "-hhmm" for time t.
+        If the current UTC offset does not represent an integer number
+        of minutes, the fractional component will be truncated."""
         off = localtime(t).tm_gmtoff
-        hrs = off / 60 / 60
-        return "%+03d%02d" % (hrs, abs(off - (hrs * 60 * 60)))
+        # Note: // doesn't truncate like C for negative values, it rounds down.
+        offmin = abs(off) // 60
+        m = offmin % 60
+        h = (offmin - m) // 60
+        return "%+03d%02d" % (-h if off < 0 else h, m)
     def to_py_time(x):
         if isinstance(x, time.struct_time):
             return x
@@ -1063,3 +1090,22 @@ else:
         return time.strftime('%z', localtime(t))
     def to_py_time(x):
         return x
+
+
+_some_invalid_save_parts_rx = re.compile(r'[[ ~^:?*\\]|\.\.|//|@{')
+
+def valid_save_name(name):
+    # Enforce a superset of the restrictions in git-check-ref-format(1)
+    if name == '@' \
+       or name.startswith('/') or name.endswith('/') \
+       or name.endswith('.'):
+        return False
+    if _some_invalid_save_parts_rx.search(name):
+        return False
+    for c in name:
+        if ord(c) < 0x20 or ord(c) == 0x7f:
+            return False
+    for part in name.split('/'):
+        if part.startswith('.') or part.endswith('.lock'):
+            return False
+    return True