view textshaper/corename.py @ 47:6c7ca72777af

add a test all convenience
author Jeff Hammel <k0scist@gmail.com>
date Sat, 16 May 2015 19:02:03 -0700
parents 8addd6e12b29
children
line wrap: on
line source

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
echo core name of files
"""

# imports
import argparse
import os
import sys

# module globals
__all__ = ['main', 'Parser']

def ensure_dir(directory):
    """ensure a directory exists"""
    if os.path.exists(directory):
        if not os.path.isdir(directory):
            raise OSError("Not a directory: '{}'".format(directory))
        return directory
    os.makedirs(directory)
    return directory


class Parser(argparse.ArgumentParser):
    """CLI option parser"""
    def __init__(self, **kwargs):
        kwargs.setdefault('formatter_class', argparse.RawTextHelpFormatter)
        kwargs.setdefault('description', __doc__)
        argparse.ArgumentParser.__init__(self, **kwargs)
        self.add_argument('files', nargs='*',
                          help="files, else read from stdin")
        self.options = None

    def parse_args(self, *args, **kw):
        options = argparse.ArgumentParser.parse_args(self, *args, **kw)
        self.validate(options)
        self.options = options
        return options

    def validate(self, options):
        """validate options"""

def main(args=sys.argv[1:]):
    """CLI"""

    # parse command line options
    parser = Parser()
    options = parser.parse_args(args)

    if not options.files:
        options.files = sys.stdin.read().strip().split()

    corenames = [os.path.splitext(os.path.basename(f))[0]
                 for f in options.files]
    print (" ".join(corenames))

if __name__ == '__main__':
    main()