Add noms.copy.Peers()

As I was working on making deployment files get staged by Go/Python,
another pattern emerged. It seems like it will be not-uncommon to want
to stage all the files in the directory your script is in over to the
staging directory the system made for you. So, provide a helper to do
that.
This commit is contained in:
Chris Masone
2015-12-15 13:38:47 -08:00
parent a47edc8431
commit 51bcb98784
3 changed files with 66 additions and 2 deletions

28
tools/noms/copy.py Normal file
View File

@@ -0,0 +1,28 @@
#!/usr/bin/python
import os.path, shutil
def Peers(me, dstDir):
"""Peers copies the peers of me into dstDir.
Peers looks for files, directories and symlinks next to me
and copies them (with the same basenames) to dstDir, which is
presumed to exist.
"""
myDir = os.path.dirname(os.path.abspath(me))
names = os.listdir(myDir)
for basename in names:
src = os.path.join(myDir, basename)
dst = os.path.join(dstDir, basename)
if os.path.samefile(me, src):
continue
if os.path.islink(src):
linkto = os.readlink(src)
os.symlink(linkto, dst)
elif os.path.isfile(src):
shutil.copy2(src, dst)
elif os.path.isdir(src):
shutil.copytree(src, dst)
else:
raise Exception("Unknown file type at " + src)

38
tools/noms/copy_test.py Normal file
View File

@@ -0,0 +1,38 @@
#!/usr/bin/python
import os, os.path, shutil, tempfile, unittest
import copy
class TestCopy(unittest.TestCase):
def setUp(self):
self.tempdir = os.path.realpath(tempfile.mkdtemp())
def tearDown(self):
shutil.rmtree(self.tempdir, ignore_errors=True)
def test_CopyPeers(self):
nested = tempfile.mkdtemp(dir=self.tempdir)
otherNested = tempfile.mkdtemp(dir=self.tempdir)
def mkfile():
ret = tempfile.NamedTemporaryFile(dir=nested, delete=False)
ret.close()
return ret.name
me = mkfile()
peerFile = os.path.basename(mkfile())
peerDir = os.path.basename(tempfile.mkdtemp(dir=nested))
peerLink = 'link'
peerLinkAbs = os.path.join(nested, 'link')
os.symlink(peerFile, peerLinkAbs)
copy.Peers(me, otherNested)
self.assertTrue(os.path.islink(os.path.join(otherNested, peerLink)))
self.assertTrue(os.path.isfile(os.path.join(otherNested, peerFile)))
self.assertTrue(os.path.isdir(os.path.join(otherNested, peerDir)))
if __name__ == '__main__':
unittest.main()

View File

@@ -4,8 +4,6 @@ import os, os.path, shutil, tempfile, unittest
import staging
class TestStaging(unittest.TestCase):
CONTENTS = 'test file contents'
def setUp(self):
self.tempdir = os.path.realpath(tempfile.mkdtemp())
self.nested = tempfile.mkdtemp(dir=self.tempdir)