aboutsummaryrefslogtreecommitdiffstats
path: root/natargs.py
blob: 664db9e5edeea76a45459e247d8ed6733bc275dc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
###########################################################################
#
###########################################################################

import sys

class DuplicateArgumentException:
	def __str__(self):
		return f"{self.oldargs} already exists"
	def __init__(self, oldargs):
		self.oldargs = oldargs

class TrieElem:
	def dochk(self, l):
		return True if self.chk is None \
		       else self.chk(len(l))

	def __init__(self, chk, f, st):
		self.chk = chk
		self.f = f
		self.st = st

def addargs(dic, oldargs, args, chk, f):
	if len(args) == 1:
		if args[0] in dic:
			raise DuplicateArgumentException(oldargs)
		else:
			dic[args[0]] = TrieElem(chk,f,{})
	else:
		if args[0] not in dic:
			dic[args[0]] = TrieElem(None, None, {})
		dic[args[0]].st = addargs(dic[args[0]].st, \
		                  oldargs, args[1:], chk, f)
	return dic

def getarg(dict, l):
	if len(l) == 0 or l[0] not in dict:
		return None
	else:
		resolved = getarg(dict[l[0]].st, l[1:])
		if resolved is None:
			if dict[l[0]].f is None:
				return None
			return dict[l[0]].f,l[1:] \
			       if dict[l[0]].dochk(l[1:]) \
			       else None
		else:
			return resolved

class Arguments:
	def usage(self, i):
		print(self.ustr)
		sys.exit(i)
	def execarg(self, args):
		res = getarg(self.trie, args)
		if res is None:
			self.usage(1)
		return res[0](res[1])

	def addarg(self, args, chk, f):
		if args == []:
			raise ValueError
		self.trie = addargs(self.trie, args, args, chk, f)

	def __init__(self, us):
		self.trie = {}
		self.ustr = us