Skip to contentSkip to conversation

git-p4: add support for large file systems

PATCH Superseded [email protected] 3 participants 10 messages Jun 15, 2016 Documentation

v6 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v6 cover git-p4: add support for large file systems

From: Lars Schneider <[email protected]>

diff to v5:
* remove superfluous flush call (thanks Luke!)
* keep &&-chain intact in test cases (thanks Luke, Junio and Eric!)
* add mock LFS test case for deleting files (thanks Luke!)
* add mock LFS test case for git-p4.largeFileExtensions option
* add Luke's ACK to commit "git-p4: add optional type specifier to gitConfig reader" (thanks Luke!)
* replace substring extraction in test case ... "${VAR:X:Y}" only works in bash, "$(echo "$VAR" | cut -cX-Y)" works in sh

Cheers,
Lars

Lars Schneider (7):
git-p4: add optional type specifier to gitConfig reader
git-p4: add gitConfigInt reader
git-p4: return an empty list if a list config has no values
git-p4: add file streaming progress in verbose mode
git-p4: check free space during streaming
git-p4: add support for large file systems
git-p4: add Git LFS backend for large file system

 Documentation/git-p4.txt   |  32 +++++
 git-p4.py                  | 278 ++++++++++++++++++++++++++++++++++++++++---
 t/t9823-git-p4-mock-lfs.sh | 170 ++++++++++++++++++++++++++
 t/t9824-git-p4-git-lfs.sh  | 288 +++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 751 insertions(+), 17 deletions(-)
 create mode 100755 t/t9823-git-p4-mock-lfs.sh
 create mode 100755 t/t9824-git-p4-git-lfs.sh

--
2.5.1

#1 lore raw

PATCH v6 1/7 git-p4: add optional type specifier to gitConfig reader

From: Lars Schneider <[email protected]>

The functions “gitConfig” and “gitConfigBool” are almost identical. Make “gitConfig” more generic by adding an optional type specifier. Use the type specifier “—bool” with “gitConfig” to implement “gitConfigBool. This prepares the implementation of other type specifiers such as “—int”.

---
 git-p4.py | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
git-p4.py +6 -6
index 073f87b..c139cab 100755
@@ -604,9 +604,12 @@ def gitBranchExists(branch):
 
 _gitConfig = {}
 
-def gitConfig(key):
+def gitConfig(key, typeSpecifier=None):
     if not _gitConfig.has_key(key):
-        cmd = [ "git", "config", key ]
+        cmd = [ "git", "config" ]
+        if typeSpecifier:
+            cmd += [ typeSpecifier ]
+        cmd += [ key ]
         s = read_pipe(cmd, ignore_error=True)
         _gitConfig[key] = s.strip()
     return _gitConfig[key]
@@ -617,10 +620,7 @@ def gitConfigBool(key):
        in the config."""
 
     if not _gitConfig.has_key(key):
-        cmd = [ "git", "config", "--bool", key ]
-        s = read_pipe(cmd, ignore_error=True)
-        v = s.strip()
-        _gitConfig[key] = v == "true"
+        _gitConfig[key] = gitConfig(key, '--bool') == "true"
     return _gitConfig[key]
 
 def gitConfigList(key):
Signature · 1 line
2.5.1
#2 lore raw

PATCH v6 2/7 git-p4: add gitConfigInt reader

In reply to [email protected]

From: Lars Schneider <[email protected]>

Add a git config reader for integer variables. Please note that the git config implementation automatically supports k, m, and g suffixes.

---
 git-p4.py | 11 +++++++++++
 1 file changed, 11 insertions(+)
git-p4.py +11 -0
index c139cab..40ad4ae 100755
@@ -623,6 +623,17 @@ def gitConfigBool(key):
         _gitConfig[key] = gitConfig(key, '--bool') == "true"
     return _gitConfig[key]
 
+def gitConfigInt(key):
+    if not _gitConfig.has_key(key):
+        cmd = [ "git", "config", "--int", key ]
+        s = read_pipe(cmd, ignore_error=True)
+        v = s.strip()
+        try:
+            _gitConfig[key] = int(gitConfig(key, '--int'))
+        except ValueError:
+            _gitConfig[key] = None
+    return _gitConfig[key]
+
 def gitConfigList(key):
     if not _gitConfig.has_key(key):
         s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
Signature · 1 line
2.5.1
#3 lore raw

PATCH v6 3/7 git-p4: return an empty list if a list config has no values

In reply to [email protected]

From: Lars Schneider <[email protected]>

---
 git-p4.py | 2 ++
 1 file changed, 2 insertions(+)
git-p4.py +2 -0
index 40ad4ae..90d3b90 100755
@@ -638,6 +638,8 @@ def gitConfigList(key):
     if not _gitConfig.has_key(key):
         s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
         _gitConfig[key] = s.strip().split(os.linesep)
+        if _gitConfig[key] == ['']:
+            _gitConfig[key] = []
     return _gitConfig[key]
 
 def p4BranchesInGit(branchesAreInRemotes=True):
Signature · 1 line
2.5.1
#4 lore raw

PATCH v6 4/7 git-p4: add file streaming progress in verbose mode

In reply to [email protected]

From: Lars Schneider <[email protected]>

If a file is streamed from P4 to Git then the verbose mode prints continuously the progress as percentage like this:
//depot/file.bin 20% (10 MB)

Upon completion the progress is overwritten with depot source, local file and size like this:
//depot/file.bin --> local/file.bin (10 MB)

---
 git-p4.py | 20 ++++++++++++++++++--
 1 file changed, 18 insertions(+), 2 deletions(-)
git-p4.py +18 -2
index 90d3b90..e7a7ea4 100755
@@ -2164,7 +2164,9 @@ class P4Sync(Command, P4UserMap):
     def streamOneP4File(self, file, contents):
         relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
         if verbose:
-            sys.stderr.write("%s\n" % relPath)
+            size = int(self.stream_file['fileSize'])
+            sys.stdout.write('\r%s --> %s (%i MB)\n' % (file['depotFile'], relPath, size/1024/1024))
+            sys.stdout.flush()
 
         (type_base, type_mods) = split_p4_type(file["type"])
 
@@ -2241,7 +2243,8 @@ class P4Sync(Command, P4UserMap):
     def streamOneP4Deletion(self, file):
         relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
         if verbose:
-            sys.stderr.write("delete %s\n" % relPath)
+            sys.stdout.write("delete %s\n" % relPath)
+            sys.stdout.flush()
         self.gitStream.write("D %s\n" % relPath)
 
     # handle another chunk of streaming data
@@ -2281,10 +2284,23 @@ class P4Sync(Command, P4UserMap):
         # 'data' field we need to append to our array
         for k in marshalled.keys():
             if k == 'data':
+                if 'streamContentSize' not in self.stream_file:
+                    self.stream_file['streamContentSize'] = 0
+                self.stream_file['streamContentSize'] += len(marshalled['data'])
                 self.stream_contents.append(marshalled['data'])
             else:
                 self.stream_file[k] = marshalled[k]
 
+        if (verbose and
+            'streamContentSize' in self.stream_file and
+            'fileSize' in self.stream_file and
+            'depotFile' in self.stream_file):
+            size = int(self.stream_file["fileSize"])
+            if size > 0:
+                progress = 100*self.stream_file['streamContentSize']/size
+                sys.stdout.write('\r%s %d%% (%i MB)' % (self.stream_file['depotFile'], progress, int(size/1024/1024)))
+                sys.stdout.flush()
+
         self.stream_have_file_info = True
 
     # Stream directly from "p4 files" into "git fast-import"
Signature · 1 line
2.5.1
#5 lore raw

PATCH v6 5/7 git-p4: check free space during streaming

In reply to [email protected]

From: Lars Schneider <[email protected]>

git-p4 will just halt if there is not enough disk space while streaming content from P4 to Git. Add a check to ensure at least 4 times (arbitrarily chosen) the size of a streamed file is available.

---
 git-p4.py | 27 ++++++++++++++++++++++++++-
 1 file changed, 26 insertions(+), 1 deletion(-)
git-p4.py +26 -1
index e7a7ea4..b465356 100755
@@ -104,6 +104,16 @@ def chdir(path, is_client_path=False):
         path = os.getcwd()
     os.environ['PWD'] = path
 
+def calcDiskFree(dirname):
+    """Return free space in bytes on the disk of the given dirname."""
+    if platform.system() == 'Windows':
+        free_bytes = ctypes.c_ulonglong(0)
+        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
+        return free_bytes.value
+    else:
+        st = os.statvfs(dirname)
+        return st.f_bavail * st.f_frsize
+
 def die(msg):
     if verbose:
         raise Exception(msg)
@@ -2038,6 +2048,14 @@ class P4Sync(Command, P4UserMap):
         self.clientSpecDirs = None
         self.tempBranches = []
         self.tempBranchLocation = "git-p4-tmp"
+        self.largeFileSystem = None
+        self.cloneDestination = None
+
+        if gitConfig('git-p4.largeFileSystem'):
+            largeFileSystemConstructor = globals()[gitConfig('git-p4.largeFileSystem')]
+            self.largeFileSystem = largeFileSystemConstructor(
+                lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)
+            )
 
         if gitConfig("git-p4.syncFromOrigin") == "false":
             self.syncWithOrigin = False
@@ -2256,6 +2274,14 @@ class P4Sync(Command, P4UserMap):
             if marshalled["code"] == "error":
                 if "data" in marshalled:
                     err = marshalled["data"].rstrip()
+
+        if not err and self.cloneDestination and 'fileSize' in self.stream_file:
+            required_bytes = int((4 * int(self.stream_file["fileSize"])) - calcDiskFree(self.cloneDestination))
+            if required_bytes > 0:
+                err = 'Not enough space left on %s! Free at least %i MB.' % (
+                    os.path.abspath(self.cloneDestination), required_bytes/1024/1024
+                )
+
         if err:
             f = None
             if self.stream_have_file_info:
@@ -3218,7 +3244,6 @@ class P4Clone(P4Sync):
             optparse.make_option("--bare", dest="cloneBare",
                                  action="store_true", default=False),
         ]
-        self.cloneDestination = None
         self.needsGit = False
         self.cloneBare = False
 
Signature · 1 line
2.5.1
#6 lore raw

PATCH v6 6/7 git-p4: add support for large file systems

In reply to [email protected]

From: Lars Schneider <[email protected]>

Perforce repositories can contain large (binary) files. Migrating these repositories to Git generates very large local clones. External storage systems such as Git LFS [1], Git Fat [2], Git Media [3], git-annex [4] try to address this problem.

Add a generic mechanism to detect large files based on extension, uncompressed size, and/or compressed size.

[1] https://git-lfs.github.com/
[2] https://github.com/jedbrown/git-fat
[3] https://github.com/alebedev/git-media
[4] https://git-annex.branchable.com/

---
 Documentation/git-p4.txt   |  32 +++++++++
 git-p4.py                  | 138 +++++++++++++++++++++++++++++++++---
 t/t9823-git-p4-mock-lfs.sh | 170 +++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 330 insertions(+), 10 deletions(-)
 create mode 100755 t/t9823-git-p4-mock-lfs.sh
Documentation/git-p4.txt +32 -0
index 82aa5d6..3f21e95 100644
@@ -510,6 +510,38 @@ git-p4.useClientSpec::
 	option '--use-client-spec'.  See the "CLIENT SPEC" section above.
 	This variable is a boolean, not the name of a p4 client.
 
+git-p4.largeFileSystem::
+	Specify the system that is used for large (binary) files. Please note
+	that large file systems do not support the 'git p4 submit' command.
+	Only Git LFS [1] is implemented right now. Download
+	and install the Git LFS command line extension to use this option
+	and configure it like this:
++
+-------------
+git config       git-p4.largeFileSystem GitLFS
+-------------
++
+	[1] https://git-lfs.github.com/
+
+git-p4.largeFileExtensions::
+	All files matching a file extension in the list will be processed
+	by the large file system. Do not prefix the extensions with '.'.
+
+git-p4.largeFileThreshold::
+	All files with an uncompressed size exceeding the threshold will be
+	processed by the large file system. By default the threshold is
+	defined in bytes. Add the suffix k, m, or g to change the unit.
+
+git-p4.largeFileCompressedThreshold::
+	All files with a compressed size exceeding the threshold will be
+	processed by the large file system. This option might slow down
+	your clone/sync process. By default the threshold is defined in
+	bytes. Add the suffix k, m, or g to change the unit.
+
+git-p4.pushLargeFiles::
+	Boolean variable which defines if large files are automatically
+	pushed to a server.
+
 Submit variables
 ~~~~~~~~~~~~~~~~
 git-p4.detectRenames::
git-p4.py +128 -10

181 lines not on this page · raw message

t/t9823-git-p4-mock-lfs.sh new file +170 -0

170 lines not on this page · raw message

Signature · 1 line
2.5.1
#7 lore raw

PATCH v6 7/7 git-p4: add Git LFS backend for large file system

In reply to [email protected]

From: Lars Schneider <[email protected]>

Add example implementation including test cases for the large file system using Git LFS.

Pushing files to the Git LFS server is not tested.

---
 git-p4.py                 |  72 ++++++++++++
 t/t9824-git-p4-git-lfs.sh | 288 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 360 insertions(+)
 create mode 100755 t/t9824-git-p4-git-lfs.sh
git-p4.py +72 -0
index 05aeb2c..4e7cac5 100755
@@ -1038,6 +1038,78 @@ class MockLFS(LargeFileSystem):
             os.makedirs(remotePath)
         shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))
 
+class GitLFS(LargeFileSystem):
+    """Git LFS as backend for the git-p4 large file system.
+       See https://git-lfs.github.com/ for details."""
+
+    def __init__(self, *args):
+        LargeFileSystem.__init__(self, *args)
+        self.baseGitAttributes = []
+
+    def generatePointer(self, cloneDestination, contentFile):
+        """Generate a Git LFS pointer for the content. Return LFS Pointer file
+           mode and content which is stored in the Git repository instead of
+           the actual content. Return also the new location of the actual
+           content.
+           """
+        pointerProcess = subprocess.Popen(
+            ['git', 'lfs', 'pointer', '--file=' + contentFile],
+            stdout=subprocess.PIPE
+        )
+        pointerFile = pointerProcess.stdout.read()
+        if pointerProcess.wait():
+            os.remove(contentFile)
+            die('git-lfs pointer command failed. Did you install the extension?')
+        pointerContents = [i+'\n' for i in pointerFile.split('\n')[2:][:-1]]
+        oid = pointerContents[1].split(' ')[1].split(':')[1][:-1]
+        localLargeFile = os.path.join(
+            cloneDestination,
+            '.git', 'lfs', 'objects', oid[:2], oid[2:4],
+            oid,
+        )
+        # LFS Spec states that pointer files should not have the executable bit set.
+        gitMode = '100644'
+        return (gitMode, pointerContents, localLargeFile)
+
+    def pushFile(self, localLargeFile):
+        uploadProcess = subprocess.Popen(
+            ['git', 'lfs', 'push', '--object-id', 'origin', os.path.basename(localLargeFile)]
+        )
+        if uploadProcess.wait():
+            die('git-lfs push command failed. Did you define a remote?')
+
+    def generateGitAttributes(self):
+        return (
+            self.baseGitAttributes +
+            [
+                '\n',
+                '#\n',
+                '# Git LFS (see https://git-lfs.github.com/)\n',
+                '#\n',
+            ] +
+            ['*.' + f.replace(' ', '[:space:]') + ' filter=lfs -text\n'
+                for f in sorted(gitConfigList('git-p4.largeFileExtensions'))
+            ] +
+            ['/' + f.replace(' ', '[:space:]') + ' filter=lfs -text\n'
+                for f in sorted(self.largeFiles) if not self.hasLargeFileExtension(f)
+            ]
+        )
+
+    def addLargeFile(self, relPath):
+        LargeFileSystem.addLargeFile(self, relPath)
+        self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
+
+    def removeLargeFile(self, relPath):
+        LargeFileSystem.removeLargeFile(self, relPath)
+        self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
+
+    def processContent(self, cloneDestination, git_mode, relPath, contents):
+        if relPath == '.gitattributes':
+            self.baseGitAttributes = contents
+            return (git_mode, self.generateGitAttributes())
+        else:
+            return LargeFileSystem.processContent(self, cloneDestination, git_mode, relPath, contents)
+
 class Command:
     def __init__(self):
         self.usage = "usage: %prog [options]"
t/t9824-git-p4-git-lfs.sh new file +288 -0

288 lines not on this page · raw message

Signature · 1 line
2.5.1
#8 lore raw
In reply to [email protected]
Quoted 9 lines · On 20/09/15 21:26, [email protected] wrote:

From: Lars Schneider <[email protected]>

diff to v5:
* remove superfluous flush call (thanks Luke!)
* keep &&-chain intact in test cases (thanks Luke, Junio and Eric!)
* add mock LFS test case for deleting files (thanks Luke!)
* add mock LFS test case for git-p4.largeFileExtensions option
* add Luke's ACK to commit "git-p4: add optional type specifier to gitConfig reader" (thanks Luke!)
* replace substring extraction in test case ... "${VAR:X:Y}" only works in bash, "$(echo "$VAR" | cut -cX-Y)" works in sh

Sorry about this, but patch 6 no longer seems to apply cleanly to next (or at least not for me).

Luke

#9 lore raw
Quoted 13 lines · Luke Diamand
Quoted 11 lines · On 20/09/15 21:26, [email protected] wrote:

From: Lars Schneider <[email protected]>

diff to v5:
* remove superfluous flush call (thanks Luke!)
* keep &&-chain intact in test cases (thanks Luke, Junio and Eric!)
* add mock LFS test case for deleting files (thanks Luke!)
* add mock LFS test case for git-p4.largeFileExtensions option
* add Luke's ACK to commit "git-p4: add optional type specifier to gitConfig reader" (thanks Luke!)
* replace substring extraction in test case ... "${VAR:X:Y}" only works in bash, "$(echo "$VAR" | cut -cX-Y)" works in sh

Quoted 2 lines

Sorry about this, but patch 6 no longer seems to apply cleanly to next (or at least not for me).

Please check the conflict resolution when I push today's result out on 'pu'.