Here are the examples of the python api twisted.python.filepath.FilePath taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
163 Examples
3
Example 1
def register(self, section):
print 'REGISTER'
self.section = section
workingdir = FilePath(os.path.expanduser("~/.vertex"))
self.clientService = ClientQ2QService(
workingdir.child("q2q-certificates").path,
verifyHook=self.displayVerifyDialog,
inboundTCPPortnum=8172,
# q2qPortnum=8173,
udpEnabled=False)
self.setCurrentID(self.clientService.getDefaultFrom())
self.buddiesfile = workingdir.child("q2q-buddies.txt")
self.loadedBuddies = {}
self.parseBuddies()
3
Example 2
def main():
plugins_dir = FilePath("/run/docker/plugins/")
if not plugins_dir.exists():
plugins_dir.makedirs()
dvol_path = FilePath("/var/lib/dvol/volumes")
if not dvol_path.exists():
dvol_path.makedirs()
voluminous = Voluminous(dvol_path.path)
sock = plugins_dir.child("%s.sock" % (VOLUME_DRIVER_NAME,))
if sock.exists():
sock.remove()
adapterServer = internet.UNIXServer(
sock.path, getAdapter(voluminous))
reactor.callWhenRunning(adapterServer.startService)
reactor.run()
3
Example 3
def __init__(self, base_path, can_read=True, can_write=True):
try:
self.base = FilePath(base_path.path)
except AttributeError:
self.base = FilePath(base_path)
self.can_read, self.can_write = can_read, can_write
3
Example 4
def initialize(self):
self.archive_dir = FilePath(config.main.archive_dir)
self.report_dir = FilePath(config.main.report_dir)
self.policy_file = config.main.policy_file
self.helpers = config.helpers
3
Example 5
Project: tahoe-lafs Source File: test_encodingutil.py
def test_extend_filepath(self):
foo_bfp = FilePath(win32_other(b'C:\\foo', b'/foo'))
foo_ufp = FilePath(win32_other(u'C:\\foo', u'/foo'))
foo_bar_baz_u = win32_other(u'C:\\foo\\bar\\baz', u'/foo/bar/baz')
for foo_fp in (foo_bfp, foo_ufp):
fp = extend_filepath(foo_fp, [u'bar', u'baz'])
self.failUnlessReallyEqual(fp, FilePath(foo_bar_baz_u))
if encodingutil.use_unicode_filepath:
self.failUnlessReallyEqual(fp.path, foo_bar_baz_u)
3
Example 6
Project: Voodoo-Mock Source File: test_script.py
def test_missingTrailingNewline(self):
"""
Source which doesn't end with a newline shouldn't cause any
exception to be raised nor an error indicator to be returned by
L{check}.
"""
fName = self.mktemp()
FilePath(fName).setContent("def foo():\n\tpass\n\t")
self.assertFalse(checkPath(fName))
3
Example 7
Project: foolscap Source File: publish.py
def remote_get_incident(self, name):
if not name.startswith("incident"):
raise KeyError("bad incident name %s" % name)
incident_dir = filepath.FilePath(self._logger.logdir)
abs_fn = incident_dir.child(name).path + ".flog"
try:
fn = abs_fn + ".bz2"
if not os.path.exists(fn):
fn = abs_fn
events = flogfile.get_events(fn, ignore_value_error=True)
# note the generator isn't actually cycled yet, not until next()
header = next(events)["header"]
except EnvironmentError:
raise KeyError("no incident named %s" % name)
wrapped_events = [event["d"] for event in events]
return (header, wrapped_events)
3
Example 8
Project: mamba-framework Source File: _project.py
@decorate_output
def _write_favicon(self):
"""Write the favicon.ico file to the static directory
"""
print('Writing favicon.ico file...'.ljust(73), end='')
favicon_file = filepath.FilePath(
'{}/static/favicon.ico'.format(self.app_dir)
)
favicon_template = self._load_template_from_mamba('favicon.ico')
favicon_file.open('wb').write(favicon_template.template)
3
Example 9
Project: powerstrip Source File: test_config.py
def test_read_from_yaml_file_invalid(self):
"""
``_read_from_yaml_file`` raises ``NoConfiguration`` if the file is not valid YAML.
"""
content = "{' unclosed"
fp = FilePath(self.mktemp())
fp.setContent(content)
self.assertRaises(InvalidConfiguration, self.config._read_from_yaml_file, fp)
3
Example 10
Project: mamba-framework Source File: test_controller.py
def test_is_valid_file_works_with_filepath(self):
import os
currdir = os.getcwd()
os.chdir('../mamba/test/dummy_app/')
self.assertTrue(self.mgr.is_valid_file(
filepath.FilePath('application/controller/dummy.py')))
os.chdir(currdir)
3
Example 11
def to_filepath(path):
precondition(isinstance(path, unicode if use_unicode_filepath else basestring),
path=path)
if isinstance(path, unicode) and not use_unicode_filepath:
path = path.encode(filesystem_encoding)
if sys.platform == "win32":
_assert(isinstance(path, unicode), path=path)
if path.startswith(u"\\\\?\\") and len(path) > 4:
# FilePath normally strips trailing path separators, but not in this case.
path = path.rstrip(u"\\")
return FilePath(path)
3
Example 12
Project: tahoe-lafs Source File: test_encodingutil.py
def test_unicode_segments_from(self):
foo_bfp = FilePath(win32_other(b'C:\\foo', b'/foo'))
foo_ufp = FilePath(win32_other(u'C:\\foo', u'/foo'))
foo_bar_baz_bfp = FilePath(win32_other(b'C:\\foo\\bar\\baz', b'/foo/bar/baz'))
foo_bar_baz_ufp = FilePath(win32_other(u'C:\\foo\\bar\\baz', u'/foo/bar/baz'))
for foo_fp in (foo_bfp, foo_ufp):
for foo_bar_baz_fp in (foo_bar_baz_bfp, foo_bar_baz_ufp):
self.failUnlessReallyEqual(unicode_segments_from(foo_bar_baz_fp, foo_fp),
[u'bar', u'baz'])
3
Example 13
Project: mamba-framework Source File: test_web.py
def test_script_raises_on_invalid_file_content(self):
tmpdir = tempfile.gettempdir()
fp = filepath.FilePath('{}/test.js'.format(tmpdir))
fd = fp.open('w')
fd.write(
'/* -*- mamba-file-type: mamba-javascript */\n'
'function dummy() { console.debug(\'dummy_test\'); }'
)
fd.close()
self.assertRaises(
script.InvalidFile,
script.Script,
tmpdir + sep + 'test.js'
)
fp.remove()
3
Example 14
Project: opencanary Source File: __init__.py
def onDirChange(self, watch, path, mask):
#print path, ' dir changed', mask # or do something else!
#import pdb; pdb.set_trace()
try:
self.notifier.ignore(filepath.FilePath(self.log_dir))
except KeyError:
pass
if mask != 2:
self.reopenFiles(skipToEnd=False)
self.processAuditLines()
3
Example 15
Project: mamba-framework Source File: _project.py
@decorate_output
def _write_plugin(self):
"""Write the plugin template to the file system
"""
print('Writing Twisted plugin...'.ljust(73), end='')
plugin_file = filepath.FilePath('{}/twisted/plugins/{}'.format(
self.app_dir, '{}_plugin.py'.format(self.name.lower())
))
plugin_template = self._load_template_from_mamba('plugin')
args = {
'application': self.name.lower(),
'file': self.file
}
plugin_file.open('w').write(plugin_template.safe_substitute(**args))
3
Example 16
def __init__(self, basedir, tub, options):
# tub might be None. No network activity should be done until
# startService. Validate all options in the constructor. Do not use
# the Service/MultiService ".name" attribute (which would prevent
# having multiple instances of a single service type in the same
# server).
service.MultiService.__init__(self)
self.basedir = basedir
self.tub = tub
self.options = options
self.targetdir = filepath.FilePath(options.targetdir)
3
Example 17
def test_permissionDenied(self):
"""
If the a source file is not readable, this is reported on standard
error.
"""
sourcePath = FilePath(self.mktemp())
sourcePath.setContent('')
sourcePath.chmod(0)
err = StringIO()
count = withStderrTo(err, lambda: checkPath(sourcePath.path))
self.assertEquals(count, 1)
self.assertEquals(
err.getvalue(), "%s: Permission denied\n" % (sourcePath.path,))
3
Example 18
Project: ceph-flocker-driver Source File: test_ceph_rbd.py
def test_list_unicode(self):
"""
Images with ``unicode`` names are found.
"""
api, runner = self._basic_output()
maps = api._list_maps()
self.assertEquals(maps[u'\U0001f433'], FilePath("/dev/rbd3"))
3
Example 19
def test_write_file(self):
Controller.process = lambda _: 0
with fake_project():
self.config.parseOptions(['controller', 'test_controller'])
controller = Controller(self.config)
controller._write_controller()
controller_file = filepath.FilePath(
'application/controller/test_controller.py'
)
self.assertTrue(controller_file.exists())
controller_file.remove()
3
Example 20
Project: powerstrip Source File: test_config.py
def test_read_from_yaml_file_missing(self):
"""
``_read_from_yaml_file`` raises ``NoConfiguration`` if the file does not exist.
"""
fp = FilePath("improbable_chickens")
self.assertRaises(NoConfiguration, self.config._read_from_yaml_file, fp)
3
Example 21
Project: tahoe-lafs Source File: test_encodingutil.py
def test_quote_filepath(self):
foo_bar_fp = FilePath(win32_other(u'C:\\foo\\bar', u'/foo/bar'))
self.failUnlessReallyEqual(quote_filepath(foo_bar_fp),
win32_other("'C:\\foo\\bar'", "'/foo/bar'"))
self.failUnlessReallyEqual(quote_filepath(foo_bar_fp, quotemarks=True),
win32_other("'C:\\foo\\bar'", "'/foo/bar'"))
self.failUnlessReallyEqual(quote_filepath(foo_bar_fp, quotemarks=False),
win32_other("C:\\foo\\bar", "/foo/bar"))
if sys.platform == "win32":
foo_longfp = FilePath(u'\\\\?\\C:\\foo')
self.failUnlessReallyEqual(quote_filepath(foo_longfp),
"'C:\\foo'")
self.failUnlessReallyEqual(quote_filepath(foo_longfp, quotemarks=True),
"'C:\\foo'")
self.failUnlessReallyEqual(quote_filepath(foo_longfp, quotemarks=False),
"C:\\foo")
3
Example 22
Project: tahoe-lafs Source File: test_encodingutil.py
def test_to_filepath(self):
foo_u = win32_other(u'C:\\foo', u'/foo')
nosep_fp = to_filepath(foo_u)
sep_fp = to_filepath(foo_u + os.path.sep)
for fp in (nosep_fp, sep_fp):
self.failUnlessReallyEqual(fp, FilePath(foo_u))
if encodingutil.use_unicode_filepath:
self.failUnlessReallyEqual(fp.path, foo_u)
if sys.platform == "win32":
long_u = u'\\\\?\\C:\\foo'
longfp = to_filepath(long_u + u'\\')
self.failUnlessReallyEqual(longfp, FilePath(long_u))
self.failUnlessReallyEqual(longfp.path, long_u)
3
Example 23
def test_write_file(self):
Model.process = lambda _: 0
with fake_project():
self.config.parseOptions(['model', 'test_model', 'test'])
model = Model(self.config)
model._write_model()
model_file = filepath.FilePath(
'application/model/test_model.py'
)
self.assertTrue(model_file.exists())
model_file.remove()
3
Example 24
Project: tahoe-lafs Source File: test_encodingutil.py
def test_unicode_from_filepath(self):
foo_bfp = FilePath(win32_other(b'C:\\foo', b'/foo'))
foo_ufp = FilePath(win32_other(u'C:\\foo', u'/foo'))
foo_u = win32_other(u'C:\\foo', u'/foo')
for foo_fp in (foo_bfp, foo_ufp):
self.failUnlessReallyEqual(unicode_from_filepath(foo_fp), foo_u)
3
Example 25
def setUp(self):
self.file = tempfile.NamedTemporaryFile(delete=False)
self.file.write(less_file)
self.file.close()
self._fp = filepath.FilePath(self.file.name)
3
Example 26
Project: tahoe-lafs Source File: encodingutil.py
def extend_filepath(fp, segments):
# We cannot use FilePath.preauthChild, because
# * it has the security flaw described in <https://twistedmatrix.com/trac/ticket/6527>;
# * it may return a FilePath in the wrong mode.
for segment in segments:
fp = fp.child(segment)
if isinstance(fp.path, unicode) and not use_unicode_filepath:
return FilePath(fp.path.encode(filesystem_encoding))
else:
return fp
3
Example 27
def setUp(self):
# setup tahoe.cfg and basedir/private/introducers
# create a custom tahoe.cfg
self.basedir = os.path.dirname(self.mktemp())
c = open(os.path.join(self.basedir, "tahoe.cfg"), "w")
config = {'hide-ip':False, 'listen': 'tcp',
'port': None, 'location': None, 'hostname': 'example.net'}
write_node_config(c, config)
fake_furl = "furl1"
c.write("[client]\n")
c.write("introducer.furl = %s\n" % fake_furl)
c.write("[storage]\n")
c.write("enabled = false\n")
c.close()
os.mkdir(os.path.join(self.basedir,"private"))
self.yaml_path = FilePath(os.path.join(self.basedir, "private",
"introducers.yaml"))
3
Example 28
Project: mamba-framework Source File: test_web.py
def test_stylesheet_raises_on_invalid_file_content(self):
tmpdir = tempfile.gettempdir()
fp = filepath.FilePath('{}/test.css'.format(tmpdir))
fd = fp.open('w')
fd.write(less_file)
fd.close()
self.assertRaises(
stylesheet.InvalidFile,
stylesheet.Stylesheet,
tmpdir + sep + 'test.css'
)
fp.remove()
3
Example 29
Project: ooni-backend Source File: handlers.py
def checkForStaleReports( _time=time):
delayed_call = reactor.callLater(config.main.stale_time,
checkForStaleReports)
report_dir = FilePath(config.main.report_dir)
for report_metadata_path in \
report_dir.globChildren("*"+METADATA_EXT):
last_updated = _time.time() - \
report_metadata_path.getModificationTime()
if last_updated > config.main.stale_time:
report_id = report_metadata_path.basename().replace(
METADATA_EXT, '')
closeReport(report_id)
return delayed_call
3
Example 30
Project: mamba-framework Source File: _project.py
@decorate_output
def _generate_directory_helper(self, directory):
"""I am a helper function to avoid code repetition
"""
print('Generating {} directory...'.format(directory).ljust(73), end='')
fp = filepath.FilePath('{}/{}'.format(self.app_dir, directory))
fp.createDirectory()
3
Example 31
Project: ooni-backend Source File: handler_helpers.py
def mock_initialize(self):
self.report_dir = FilePath('.')
self.archive_dir = FilePath('.')
self.policy_file = None
self.helpers = {}
self.stale_time = 10
3
Example 32
Project: scrapy Source File: test_webclient.py
def setUp(self):
name = self.mktemp()
os.mkdir(name)
FilePath(name).child("file").setContent(b"0123456789")
r = static.File(name)
r.putChild(b"redirect", util.Redirect(b"/file"))
r.putChild(b"wait", ForeverTakingResource())
r.putChild(b"error", ErrorResource())
r.putChild(b"nolength", NoLengthResource())
r.putChild(b"host", HostHeaderResource())
r.putChild(b"payload", PayloadResource())
r.putChild(b"broken", BrokenDownloadResource())
r.putChild(b"encoding", EncodingResource())
self.site = server.Site(r, timeout=None)
self.wrapper = WrappingFactory(self.site)
self.port = self._listen(self.wrapper)
self.portno = self.port.getHost().port
3
Example 33
Project: imaginary Source File: test_actions.py
def test_helpMultiword(self):
"""
The help action supports arguments with spaces in them.
"""
fakeHelp = filepath.FilePath(self.mktemp())
fakeHelp.makedirs()
fakeHelp.child("foo bar").setContent("baz")
original = Help.helpContentPath
try:
Help.helpContentPath = fakeHelp
self._test("help foo bar", ["baz"], [])
finally:
Help.helpContentPath = original
3
Example 34
Project: mamba-framework Source File: test_mamba_admin.py
@defer.inlineCallbacks
def test_sql_dump_to_file(self):
#_check_mamba_admin_tool()
result = yield utils.getProcessValue('mamba-admin', [], os.environ)
if result == 1:
raise unittest.SkipTest('mamba framework is not installed yet')
with fake_project():
yield utils.getProcessOutput(
'mamba-admin', ['sql', 'dump', 'test'], os.environ
)
dump_file = filepath.FilePath('test.sql')
self.assertTrue(dump_file.exists())
self.assertTrue(dump_file.getsize() > 0)
dump_file.remove()
3
Example 35
def setUp(self):
self.realChunkSize = sigma.CHUNK_SIZE
sigma.CHUNK_SIZE = 100
svc = self.service = FakeQ2QService()
fname = self.mktemp()
sf = self.sfile = FilePath(fname)
if not sf.parent().isdir():
sf.parent().makedirs()
sf.open('w').write(TEST_DATA)
self.senderNexus = sigma.Nexus(svc, sender,
sigma.BaseNexusUI(self.mktemp()),
svc.callLater)
3
Example 36
Project: Voodoo-Mock Source File: test_script.py
def test_eofSyntaxError(self):
"""
The error reported for source files which end prematurely causing a
syntax error reflects the cause for the syntax error.
"""
source = "def foo("
sourcePath = FilePath(self.mktemp())
sourcePath.setContent(source)
err = StringIO()
count = withStderrTo(err, lambda: checkPath(sourcePath.path))
self.assertEqual(count, 1)
self.assertEqual(
err.getvalue(),
"""\
%s:1: unexpected EOF while parsing
def foo(
^
""" % (sourcePath.path,))
3
Example 37
def __init__(self, basedir, tubid_s, gatherer, publisher, stdout):
if not os.path.isdir(basedir):
os.makedirs(basedir)
self.basedir = filepath.FilePath(basedir)
self.tubid_s = tubid_s # printable string
self.gatherer = gatherer
self.publisher = publisher
self.stdout = stdout
self.caught_up_d = defer.Deferred()
self.incidents_wanted = []
self.incident_fetch_outstanding = False
3
Example 38
Project: mamba-framework Source File: _project.py
@decorate_output
def _write_services(self):
"""Write the mamba services template to the file system
"""
print('Writing mamba service...'.ljust(73), end='')
service_file = filepath.FilePath('{}/mamba_services.py'.format(
self.app_dir
))
service_template = self._load_template_from_mamba('mamba_services')
service_file.open('w').write(service_template.template)
3
Example 39
Project: ceph-flocker-driver Source File: test_ceph_rbd.py
def test_list_bytes(self):
"""
Images with ``bytes`` names are found.
"""
api, runner = self._basic_output()
maps = api._list_maps()
self.assertEquals(maps[u"flocker-foo"], FilePath("/dev/rbd2"))
3
Example 40
Project: Voodoo-Mock Source File: test_script.py
def test_misencodedFile(self):
"""
If a source file contains bytes which cannot be decoded, this is
reported on stderr.
"""
source = u"""\
# coding: ascii
x = "\N{SNOWMAN}"
""".encode('utf-8')
sourcePath = FilePath(self.mktemp())
sourcePath.setContent(source)
err = StringIO()
count = withStderrTo(err, lambda: checkPath(sourcePath.path))
self.assertEquals(count, 1)
self.assertEquals(
err.getvalue(), "%s: problem decoding source\n" % (sourcePath.path,))
3
Example 41
def postOptions(self):
if self.subCommand is None:
return self.opt_help()
if self["pool"] is None:
# TODO untested
homePath = FilePath("/var/lib/dvol/volumes")
if not homePath.exists():
homePath.makedirs()
self["pool"] = homePath.path
lockFactory = DockerLock
if self["disable-docker-integration"]:
# Do not attempt to connect to Docker if we've been asked not to.
lockFactory = NullLock
self.voluminous = Voluminous(self["pool"], lockFactory=lockFactory)
self.subOptions.run(self.voluminous)
3
Example 42
Project: mamba-framework Source File: commons.py
def generate_sub_packages(path_file):
"""Generate directories and __init__.py scripts for subpackages
"""
modules_dirs = filepath.FilePath(path_file.path.rsplit('/', 1)[0])
modules_dirs.makedirs()
for directory in [f for f in modules_dirs.walk() if f.isdir()]:
fp = filepath.FilePath(filepath.joinpath(f.path, '__init__.py'))
if not fp.exists():
fp.touch()
3
Example 43
Project: powerstrip Source File: test_config.py
def test_read_from_yaml_file_success(self):
"""
``_read_from_yaml_file`` returns the file's content.
"""
content = "ducks: cows"
fp = FilePath(self.mktemp())
fp.setContent(content)
result = self.config._read_from_yaml_file(fp)
self.assertEquals(result, {"ducks": "cows"})
3
Example 44
Project: tahoe-lafs Source File: client.py
def load_static_servers(self):
"""
Load the servers.yaml file if it exists, and provide the static
server data to the StorageFarmBroker.
"""
fn = os.path.join(self.basedir, "private", "servers.yaml")
servers_filepath = FilePath(fn)
try:
with servers_filepath.open() as f:
servers_yaml = yamlutil.safe_load(f)
static_servers = servers_yaml.get("storage", {})
log.msg("found %d static servers in private/servers.yaml" %
len(static_servers))
self.storage_broker.set_static_servers(static_servers)
except EnvironmentError:
pass
3
Example 45
Project: mamba-framework Source File: _project.py
@decorate_output
def _write_layout_html(self):
"""Write the layout.html Jinja2 default template
"""
print('Writting layout.html template file...'.ljust(73), end='')
layout_file = filepath.FilePath(
'{}/application/view/templates/layout.html'.format(self.app_dir)
)
layout_template = self._load_template_from_mamba('layout.tpl')
layout_file.open('wb').write(layout_template.template)
3
Example 46
@log_file.setter
def log_file(self, file):
path = filepath.FilePath(file)
if not filepath.exists(path.dirname()):
raise ApplicationError('%s' % (
'Given directory %s don\t exists' % path.dirname())
)
self._log_file = file
3
Example 47
Project: mamba-framework Source File: test_mamba_admin.py
@defer.inlineCallbacks
def test_sql_create_file(self):
result = yield utils.getProcessValue('mamba-admin', [], os.environ)
if result == 1:
raise unittest.SkipTest('mamba framework is not installed yet')
with fake_project():
yield utils.getProcessOutput(
'python',
['../../scripts/mamba_admin.py', 'sql', 'create', 'test'],
os.environ
)
dump_file = filepath.FilePath('test.sql')
self.assertTrue(dump_file.exists())
self.assertTrue(dump_file.getsize() > 0)
dump_file.remove()
3
Example 48
Project: mamba-framework Source File: test_mamba_admin.py
@defer.inlineCallbacks
def test_is_mamba_package_for_tar_file(self):
result = yield utils.getProcessValue('mamba-admin', [], os.environ)
if result == 1:
raise unittest.SkipTest('mamba framework is not installed yet')
with self._generate_docs():
self.config.parseOptions()
self.config['name'] = 'mamba-dummy'
self.packer.pack_application(
'sdist', self.config,
config.Application('config/application.json')
)
self.assertTrue(os.path.exists('mamba-dummy-0.1.2.tar.gz'))
path = filepath.FilePath('mamba-dummy-0.1.2.tar.gz')
is_mamba_package = self.packer.is_mamba_package(path)
self.assertTrue(is_mamba_package)
self.packer.do(['rm', 'mamba-dummy-0.1.2.tar.gz'])
3
Example 49
def setUp(self):
self.r = less.LessResource()
self.fd = tempfile.NamedTemporaryFile(delete=False)
self.fd.write(less_file)
self.fd.close()
self._fp = filepath.FilePath(self.fd.name)
3
Example 50
def setUp(self):
# setup tahoe.cfg and basedir/private/introducers
# create a custom tahoe.cfg
self.basedir = os.path.dirname(self.mktemp())
c = open(os.path.join(self.basedir, "tahoe.cfg"), "w")
config = {'hide-ip':False, 'listen': 'tcp',
'port': None, 'location': None, 'hostname': 'example.net'}
write_node_config(c, config)
c.write("[client]\n")
c.write("# introducer.furl =\n") # omit default
c.write("[storage]\n")
c.write("enabled = false\n")
c.close()
os.mkdir(os.path.join(self.basedir,"private"))
self.yaml_path = FilePath(os.path.join(self.basedir, "private",
"introducers.yaml"))