示例#1
0
    def __str__(self, width=None):
        if not width:
            width = int(os.environ.get('COLUMNS', '80'))

        longToShort = {}
        for key, value in self.synonyms.items():
            longname = value
            if (key != longname) and (len(key) == 1):
                longToShort[longname] = key
            else:
                if not longToShort.has_key(longname):
                    longToShort[longname] = None
                else:
                    pass

        optDicts = []
        for opt in self.longOpt:
            if opt[-1] == '=':
                optType = 'parameter'
                opt = opt[:-1]
            else:
                optType = 'flag'

            optDicts.append({
                'long': opt,
                'short': longToShort[opt],
                'doc': self.docs[opt],
                'optType': optType,
                'default': getattr(self, opt, None)
            })

        synopsis = getattr(
            self, "synopsis",
            "Usage: %s%s" % (path.basename(sys.argv[0]),
                             (optDicts and " [options]") or ''))

        if not synopsis[-len('\n'):] == '\n':
            synopsis = synopsis + '\n'

        if not (getattr(self, "longdesc", None) is None):
            longdesc = self.longdesc
        else:
            import __main__
            if getattr(__main__, '__doc__', None):
                longdesc = __main__.__doc__
            else:
                longdesc = ''

        if longdesc:
            longdesc = ('\n' +
                        string.join(text.wordWrap(longdesc, width), '\n'))

        if optDicts:
            chunks = docMakeChunks(optDicts, width)
            s = "Options:\n%s" % (string.join(chunks, ''))
        else:
            s = "Options: None\n"

        return synopsis + s + longdesc
示例#2
0
文件: usage.py 项目: lhl/songclub
    def __str__(self, width=None):
        if not width:
            width = int(os.environ.get('COLUMNS', '80'))

        longToShort = {}
        for key, value in self.synonyms.items():
            longname = value
            if (key != longname) and (len(key) == 1):
                longToShort[longname] = key
            else:
                if not longToShort.has_key(longname):
                    longToShort[longname] = None
                else:
                    pass

        optDicts = []
        for opt in self.longOpt:
            if opt[-1] == '=':
                optType = 'parameter'
                opt = opt[:-1]
            else:
                optType = 'flag'

            optDicts.append(
                {'long': opt,
                 'short': longToShort[opt],
                 'doc': self.docs[opt],
                 'optType': optType,
                 'default': getattr(self, opt, None)
                 })

        synopsis = getattr(self, "synopsis",
                           "Usage: %s%s"
                           % (path.basename(sys.argv[0]),
                              (optDicts and " [options]") or ''))

        if not synopsis[-len('\n'):] == '\n':
            synopsis = synopsis + '\n'

        if not (getattr(self, "longdesc", None) is None):
            longdesc = self.longdesc
        else:
            import __main__
            if getattr(__main__, '__doc__', None):
                longdesc = __main__.__doc__
            else:
                longdesc = ''

        if longdesc:
            longdesc = ('\n' +
                        string.join(text.wordWrap(longdesc, width), '\n'))

        if optDicts:
            chunks = docMakeChunks(optDicts, width)
            s = "Options:\n%s" % (string.join(chunks, ''))
        else:
            s = "Options: None\n"

        return synopsis + s + longdesc
示例#3
0
def docMakeChunks(optList, width=80):
    """Makes doc chunks for option declarations.

    Takes a list of dictionaries, each of which may have one or more
    of the keys 'long', 'short', 'doc', 'default', 'optType'.

    Returns a list of strings.
    The strings may be multiple lines,
    all of them end with a newline.
    """

    # XXX: sanity check to make sure we have a sane combination of keys.

    maxOptLen = 0
    for opt in optList:
        optLen = len(opt.get('long', ''))
        if optLen:
            if opt.get('optType', None) == "parameter":
                # these take up an extra character
                optLen = optLen + 1
            maxOptLen = max(optLen, maxOptLen)

    colWidth1 = maxOptLen + len("  -s, --  ")
    colWidth2 = width - colWidth1
    # XXX - impose some sane minimum limit.
    # Then if we don't have enough room for the option and the doc
    # to share one line, they can take turns on alternating lines.

    colFiller1 = " " * colWidth1

    optChunks = []
    seen = {}
    for opt in optList:
        if seen.has_key(opt.get('short', None)) \
           or seen.has_key(opt.get('long', None)):
            continue
        for x in opt.get('short', None), opt.get('long', None):
            if x is not None:
                seen[x] = 1

        optLines = []
        comma = " "
        if opt.get('short', None):
            short = "-%c" % (opt['short'], )
        else:
            short = ''

        if opt.get('long', None):
            long = opt['long']
            if opt.get("optType", None) == "parameter":
                long = long + '='

            long = "%-*s" % (maxOptLen, long)
            if short:
                comma = ","
        else:
            long = " " * (maxOptLen + len('--'))

        if opt.get('optType', None) == 'command':
            column1 = '    %s      ' % long
        else:
            column1 = "  %2s%c --%s  " % (short, comma, long)

        if opt.get('doc', ''):
            doc = opt['doc'].strip()
        else:
            doc = ''

        if (opt.get("optType", None) == "parameter") \
           and not (opt.get('default', None) is None):
            doc = "%s [default: %s]" % (doc, opt['default'])

        if doc:
            column2_l = text.wordWrap(doc, colWidth2)
        else:
            column2_l = ['']

        optLines.append("%s%s\n" % (column1, column2_l.pop(0)))

        for line in column2_l:
            optLines.append("%s%s\n" % (colFiller1, line))

        optChunks.append(string.join(optLines, ''))

    return optChunks
示例#4
0
    def getUsage(self, width=None):
        #If subOptions exists by now, then there was probably an error while
        #parsing its options.
        if hasattr(self, 'subOptions'):
            return self.subOptions.getUsage(width=width)

        if not width:
            width = int(os.environ.get('COLUMNS', '80'))

        if hasattr(self, 'subCommands'):
            cmdDicts = []
            for (cmd, short, parser, desc) in self.subCommands:
                cmdDicts.append({
                    'long': cmd,
                    'short': short,
                    'doc': desc,
                    'optType': 'command',
                    'default': None
                })
            chunks = docMakeChunks(cmdDicts, width)
            commands = 'Commands:\n' + ''.join(chunks)
        else:
            commands = ''

        longToShort = {}
        for key, value in self.synonyms.items():
            longname = value
            if (key != longname) and (len(key) == 1):
                longToShort[longname] = key
            else:
                if not longToShort.has_key(longname):
                    longToShort[longname] = None
                else:
                    pass

        optDicts = []
        for opt in self.longOpt:
            if opt[-1] == '=':
                optType = 'parameter'
                opt = opt[:-1]
            else:
                optType = 'flag'

            optDicts.append({
                'long': opt,
                'short': longToShort[opt],
                'doc': self.docs[opt],
                'optType': optType,
                'default': self.defaults.get(opt, None)
            })

        if not (getattr(self, "longdesc", None) is None):
            longdesc = self.longdesc
        else:
            import __main__
            if getattr(__main__, '__doc__', None):
                longdesc = __main__.__doc__
            else:
                longdesc = ''

        if longdesc:
            longdesc = ('\n' + string.join(text.wordWrap(longdesc, width),
                                           '\n').strip() + '\n')

        if optDicts:
            chunks = docMakeChunks(optDicts, width)
            s = "Options:\n%s" % (string.join(chunks, ''))
        else:
            s = "Options: None\n"

        return s + longdesc + commands
示例#5
0
def docMakeChunks(optList, width=80):
    """Makes doc chunks for option declarations.

    Takes a list of dictionaries, each of which may have one or more
    of the keys 'long', 'short', 'doc', 'default', 'optType'.

    Returns a list of strings.
    The strings may be multiple lines,
    all of them end with a newline.
    """

    # XXX: sanity check to make sure we have a sane combination of keys.

    maxOptLen = 0
    for opt in optList:
        optLen = len(opt.get('long', ''))
        if optLen:
            if opt.get('optType', None) == "parameter":
                # these take up an extra character
                optLen = optLen + 1
            maxOptLen = max(optLen, maxOptLen)

    colWidth1 = maxOptLen + len("  -s, --  ")
    colWidth2 = width - colWidth1
    # XXX - impose some sane minimum limit.
    # Then if we don't have enough room for the option and the doc
    # to share one line, they can take turns on alternating lines.

    colFiller1 = " " * colWidth1

    optChunks = []
    seen = {}
    for opt in optList:
        if seen.has_key(opt.get('short', None)) \
           or seen.has_key(opt.get('long', None)):
            continue
        for x in opt.get('short', None), opt.get('long', None):
            if x is not None:
                seen[x]=1

        optLines = []
        comma = " "
        if opt.get('short', None):
            short = "-%c" % (opt['short'],)
        else:
            short = ''

        if opt.get('long', None):
            long = opt['long']
            if opt.get("optType", None) == "parameter":
                long = long + '='

            long = "%-*s" % (maxOptLen, long)
            if short:
                comma = ","
        else:
            long = " " * (maxOptLen + len('--'))

        if opt.get('optType', None) == 'command':
            column1 = '    %s      ' % long
        else:
            column1 = "  %2s%c --%s  " % (short, comma, long)

        if opt.get('doc', ''):
            doc = opt['doc'].strip()
        else:
            doc = ''

        if (opt.get("optType", None) == "parameter") \
           and not (opt.get('default', None) is None):
            doc = "%s [default: %s]" % (doc, opt['default'])

        if doc:
            column2_l = text.wordWrap(doc, colWidth2)
        else:
            column2_l = ['']

        optLines.append("%s%s\n" % (column1, column2_l.pop(0)))

        for line in column2_l:
            optLines.append("%s%s\n" % (colFiller1, line))

        optChunks.append(string.join(optLines, ''))

    return optChunks
示例#6
0
    def getUsage(self, width=None):
        #If subOptions exists by now, then there was probably an error while
        #parsing its options.
        if hasattr(self, 'subOptions'):
            return self.subOptions.getUsage(width=width)

        if not width:
            width = int(os.environ.get('COLUMNS', '80'))

        if hasattr(self, 'subCommands'):
            cmdDicts = []
            for (cmd, short, parser, desc) in self.subCommands:
                cmdDicts.append(
                    {'long': cmd,
                     'short': short,
                     'doc': desc,
                     'optType': 'command',
                     'default': None
                    })
            chunks = docMakeChunks(cmdDicts, width)
            commands = 'Commands:\n' + ''.join(chunks)
        else:
            commands = ''

        longToShort = {}
        for key, value in self.synonyms.items():
            longname = value
            if (key != longname) and (len(key) == 1):
                longToShort[longname] = key
            else:
                if not longToShort.has_key(longname):
                    longToShort[longname] = None
                else:
                    pass

        optDicts = []
        for opt in self.longOpt:
            if opt[-1] == '=':
                optType = 'parameter'
                opt = opt[:-1]
            else:
                optType = 'flag'

            optDicts.append(
                {'long': opt,
                 'short': longToShort[opt],
                 'doc': self.docs[opt],
                 'optType': optType,
                 'default': self.defaults.get(opt, None)
                 })

        if not (getattr(self, "longdesc", None) is None):
            longdesc = self.longdesc
        else:
            import __main__
            if getattr(__main__, '__doc__', None):
                longdesc = __main__.__doc__
            else:
                longdesc = ''

        if longdesc:
            longdesc = ('\n' +
                        string.join(text.wordWrap(longdesc, width), '\n').strip()
                        + '\n')

        if optDicts:
            chunks = docMakeChunks(optDicts, width)
            s = "Options:\n%s" % (string.join(chunks, ''))
        else:
            s = "Options: None\n"

        return s + longdesc + commands