def create_dir(path, mode=0777): """Ensure that a directory exists at path. Parent directories are created if needed. :param path: Directory to create if it does not exist. :param mode: Mode for newly created parent directories. :param return: ``False`` if the path existed, ``True`` otherwise. """ npath = remote.path.normpath(path) st = remote.stat(path) if not st: head, tail = remote.path.split(path) if tail and head: # create parent directories create_dir(head, mode) remote.mkdir(npath, mode) return Changed(msg='Created directory: {}'.format(path)) return Unchanged('Already exists: {}'.format(path))
def remote_tmpdir(delete=True, randbytes=16, mode=0o700): # FIXME: audit this for security issues if config['cmd_mktemp']: # create directory using mktemp command tmpdir, _, _ = proc.run([config['cmd_mktemp'], '-d']) tmpdir = tmpdir.rstrip('\n') else: # emulate mktemp tmpdir = remote.path.join(config['fs_fallback_tmpdir'], 'remand-' + hexlify(os.urandom(randbytes))) remote.mkdir(tmpdir, mode=mode) log.debug('Created temporary directory {}'.format(tmpdir)) try: yield tmpdir finally: if delete: log.debug('Removing temporary directory {}'.format(tmpdir)) remove_dir(tmpdir)
def run(): log.warning('Running testing module. Do not run this on a real machine!') log.debug('Testing popen') proc = remote.popen(['uname']) stdout, stderr = proc.communicate() assert 'Linux' == stdout.strip() log.debug('Testing getcwd()') assert '/home/vagrant' == remote.getcwd() log.debug('Testing chdir()') remote.chdir('/') assert '/' == remote.getcwd() remote.chdir('/home/vagrant') # create a sample file TESTFN = 'testfile' TESTDN = 'TESTDIR' log.debug('Testing file') with remote.file(TESTFN, mode='w') as out: out.write('test') log.debug('Testing chmod') remote.chmod(TESTFN, 0732) log.debug('Testing mkdir') # FIXME: umask? # FIXME: on exists/conflict? remote.mkdir(TESTDN, 0700) log.debug('Testing listdir') assert TESTFN in remote.listdir('.') assert TESTDN in remote.listdir('.') log.debug('Testing rmdir') remote.rmdir(TESTDN) # FIXME: can't test chown without root access log.debug('Testing normalize') assert '/home' == remote.normalize('./..') log.debug('Testing symlink') remote.symlink('to', 'from') log.debug('Testing lstat') remote.lstat('from') log.debug('Testing readlink') assert remote.readlink('/home/vagrant/from') == 'to' log.debug('Testing rename') remote.rename('from', 'from2') assert remote.readlink('/home/vagrant/from2') == 'to' log.debug('Testing unlink') remote.unlink('/home/vagrant/from2') log.debug('Testing stat') s = remote.stat(TESTFN) assert s.st_uid == 1000 assert s.st_gid == 1000 remote.unlink(TESTFN)