<commit_before>#!/usr/bin/env python
""" sshfs.py is a simple interface around the sshfs tool to help manage
    multiple sshfs mountpoints.
"""
import sys, optparse, commands, os

def _getMountPoints():
    """Run the bash command: grep sshfs /etc/mtab | cut -f 2 -d ' '; to get
       the list of sshfs mount points.
    """
    mountpoints = commands.getoutput("grep sshfs /etc/mtab | cut -f 2 -d ' '").strip().split()
    if not mountpoints:
        print "No mounts found"
        sys.exit(0)

    mountpoints.sort()
    return mountpoints

def _executeCommand(cmd):
    """Execute a bash command and print the results."""
    status, output = commands.getstatusoutput(cmd)
    if status == 0:
        return 0
    print "Failure:"
    print output
    return status

def _prepareDestination(dest):
    """Make sure the destination directory exists. """
    if not os.path.exists(dest):
        _executeCommand('mkdir -p %s' % dest)

def listMounts(opts):
    """List the existing sshfs mountpoints on the system."""
    mountpoints = _getMountPoints()
    print '\n'.join(['%s: %s' % (count, mnt) for count, mnt in enumerate(mountpoints)])
    return 0

def mount(opts):
    """Create an sshfs mount point."""
    _prepareDestination(opts.args[-1])
    cmd = 'sshfs -o nonempty -o allow_other -o kernel_cache -o auto_cache -o reconnect -o follow_symlinks -o transform_symlinks %s' % ' '.join(opts.args)
    print 'Creating mountpoint: %s' % opts.args[-1]
    return _executeCommand(cmd)

def unmount(opts):
    """Remove an existing sshfs mountpoint and clean up the target dir """
    cmdStr = "fusermount -u %s"
    mountpoints = _getMountPoints()

    cmd = ''
    target = opts.args.pop(0)
    if os.path.exists(target) and target in mountpoints:
        cmd = cmdStr % target
    elif len(target) == 1:
        try:
            targetIndex = int(target)
        except:
            print "Could not interpret which mountpoint to remove: %s" % target
            sys.exit(1)
        target = mountpoints.pop(targetIndex)
        cmd = cmdStr % target
    print  "Removing mountpoint: %s" % target
    if _executeCommand(cmd) == 0:
        os.rmdir(target)
        return 0
    return 1

def parseCmdLine(defaultAction):
    """
    manage cli invocation
    """
    usage = '%prog [action] [options]'
    version = '%prog v0.1'
    description = __doc__
    parser = optparse.OptionParser(usage=usage, version=version,
                                   description=description )
    parser.add_option('-m', '--mount', dest='action', action='store_const',
                      const=mount, help="Create new mount point. Uses the same syntax as sshfs.")
    parser.add_option('-u', '--unmount', dest='action', action='store_const',
                      const=unmount, help="Remove an existing mountpoint.")
    parser.add_option('-l', '--list', dest='action', action='store_const',
                      const=listMounts, help="List existing mountpoints. [default action]")

    opts, args = parser.parse_args()
    if not opts.action:
        opts.action = defaultAction

    opts.args = args

    return opts

def main():
    """ Execute the script.
    """
    opts = parseCmdLine(defaultAction=listMounts)

    return opts.action(opts)


if __name__ == '__main__':
    sys.exit(main())<commit_msg>sshfs: rewrote script to be more OO and useful as a library<commit_after>#!/usr/bin/env python
"""
Provides a wrapper around the 'sshfs' and 'fusermount' utilities to simplify
interactions with SSHFS mounts.
"""
import re
import os
import sys
import argparse
import commands
from itertools import chain

VERSION = 'v0.1'


def main():
    parser = argparse.ArgumentParser(version=VERSION, description=__doc__)
    opts, args = parser.parse_known_args()

    sshfs = SSHFS()
    if len(args) == 0:
        sshfs.list_mountpoints()
    elif len(args) == 1:
        sshfs.unmount(args[0])
    elif len(args) == 2:
        sshfs.mount(args[0], args[1])


class Mountpoints(list):

    @staticmethod
    def load():
        mountpoints = Mountpoints()
        with open('/etc/mtab', 'r') as fin:
            for line in fin.readlines():
                if re.search('sshfs', line):
                    mountpoints.append(line.split(' ')[1])
        mountpoints.sort()
        return mountpoints

    def __str__(self):
        return '\n'.join(['%s: %s' % (count, mountpoint) for
                          count, mountpoint in enumerate(self)])


class SSHFS(object):

    def __init__(self):
        self.mountpoints = None
        self._load_mountpoints()
        self.sshfs_binary = '/usr/bin/sshfs'
        self.fusermount_binary = '/usr/bin/fusermount'
        self.mount_options = ['nonempty', 'allow_other', 'kernel_cache',
                              'auto_cache', 'reconnect', 'follow_symlinks',
                              'transform_symlinks']

    def _load_mountpoints(self):
        self.mountpoints = Mountpoints.load()

    def list_mountpoints(self):
        print self.mountpoints

    def _format_mount_options(self):
        return list(chain.from_iterable(zip(['-o'] * len(self.mount_options),
                                            self.mount_options)))

    def mount(self, source, dest):
        command = ([self.sshfs_binary] +
                   self._format_mount_options() +
                   [source, dest])
        if not os.path.exists(dest):
            os.mkdir(dest)
        _execute(command)
        self._load_mountpoints()

    def unmount(self, mountpoint):
        """Mountpoint can either be a path or an index for self.mountpoints"""
        err_msg = ("The given mountpoint '%s' doesn't appear to exist." %
                   mountpoint)
        if isinstance(mountpoint, int):
            try:
                mountpoint = self.mountpoints[mountpoint]
            except IndexError:
                raise Exception(err_msg)
        elif not os.path.exists(mountpoint):
            raise Exception(err_msg)

        command = [self.fusermount_binary, '-u', mountpoint]
        _execute(command)

        try: # remove mountpoint if empty
            os.rmdir(mountpoint)
        except OSError, e: # ignore error if directory not empty
            if e.args[0] == 39 and 'not empty' in e.args[1].lower():
                pass
        self._load_mountpoints()


def _execute(cmd):
    """Execute a bash command and print the results."""
    if isinstance(cmd, list):
        cmd = ' '.join(cmd)
    status, output = commands.getstatusoutput(cmd)
    if status == 0:
        return 0
    print "Failure:"
    print output
    return status


if __name__ == '__main__':
    sys.exit(main())
{'fraction_non_alphanumeric': 0.11721336142040326, 'fraction_numerical': 0.004664459825458923, 'mean_word_length': 2.3982617586912065, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2286775', 'n_tokens_mistral': 2019, 'n_tokens_neox': 1924, 'n_words': 555}