summaryrefslogtreecommitdiff
path: root/uio.py
blob: e34fcfda8e44951ad9a6e9f5ee4f4f833a30e404 (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python
# Copyright 1999-2009 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# Universal Select Tool
# Uselect Input/Output Module
# uio.py mephx.x@gmail.com

import os
import pwd
import stat
import subprocess


# Aligning
space = ' '
right = '\t'

# Globals
bold = lime = red = reset = yellow = notice = ''
error = warning =  bullet = ok = highlight = ''

verbose = False

class Counter:
	
	def __init__(self):
		self.count = 0
		self.level = 0
	
class FileSystem:
	""" FileSystem Class """
	def __init__(self):
		""" FileSystem Contructor """
		self.home = os.getenv('HOME')
		self.set_global = False
		self.uid = pwd.getpwuid(os.getuid())[0]
		self.environment = self.home + '/.uselect/'
	
	def set_type(self, type):
		if type == 'profile':
			self.environment = './.uprofile/'
	def create_dir(self, target):
		"""Recursively creates directories"""
		if not os.path.exists(target):
			os.makedirs(target)
			
	def prepare_environment(self):
		if not os.path.exists(self.environment):
			os.mkdir(self.environment)
		if not os.path.exists(self.environment + 'bin/'):
			os.mkdir(self.environment + 'bin/')
		if not os.path.exists(self.environment + 'env.d/'):
			os.mkdir(self.environment + 'env.d/')
	def get_env(self):
		env = []
		for param in os.environ.keys():
			env.append([param,os.environ[param]])
		return env
		
	def set_env(self, env):
		""" Re-set a environment variable """
		# Only changes uselects environment !BROKEN!
		os.environ[env.name] = env.to_string()
	
	def read_file(self, path):
		""" Reads a File and returns lines[] """
		file = open(path,'r')
		lines = file.readlines()
		file.close
		return lines

	def write_file(self, path ,lines):
		""" Writes "lines[]" in File "path" """
		if os.path.exists(path):
			raise Exception("File in " + path + " already Exists!")
			return
		file = open(path,'w')
		for line in lines:
			file.writelines(line + '\n')
		file.close
		return lines
		
	def execute_cmd(self, cmd, args):
		""" Executes "cmd" and returns output """
		if not os.path.exists(cmd):
			raise Exception('File "' + path + '" not found!')
			return
		for arg in args:
			cmd += ' ' + arg
		# TODO: change to subprocess.Popen
		return os.popen(cmd)
		
	def delete_file(self, path):
		""" Deletes file in "path" """
		if os.path.exists(path):
			os.unlink(path)

	def make_exec_file(self, path):
		""" Makes file in path u+rwx """
		if not os.path.exists(path):
			raise Exception('File "' + path + '" not found!')
			return
		os.chmod(path, stat.S_IXUSR + stat.S_IRUSR + stat.S_IWUSR)
	
	def create_symlink(self, source, destination):
		self.delete_file(destination)
		os.symlink(source, destination)
	
	def list_dir(self, path):
		""" Lists path directory """
		if not os.path.exists(path):
			raise Exception("File " + path + " not found!")
			return
		else:
			return os.listdir(path)
			
	def path_exists(self, path):
		return os.path.exists(path)
		
	def real_path(self, path):
		return os.path.realpath(path)

	
class PrintSystem:
	""" PrintSystem Class """
	
	def set_type(self, type):
		if type == 'profile':
			self.__class__ = ProfilePrintSystem
		
	def __init__(self, profile = False):
		""" PrintSystem Constructor """
		if profile:
			self.__class__ = ProfilePrintSystem
		return
		
	def verbose(self):
		global verbose
		verbose = True
		return
		
	def use_colors(self, usecolors):
		global bold, lime, red, reset, yellow, error, warning, bullet,\
			ok, highlight, notice
		if usecolors:
			# Text Colors
			bold = '\033[1m'
			lime = '\033[32m'
			red = '\033[31m'
			reset = '\033[0m'
			yellow = '\033[1;33m'
			blue = '\033[1;34m'
			# Bullets
		else:
			bold = lime = red = reset =	yellow = ''
			
		error = bold + '(' + red + '!' + reset + bold + ')' + reset
		warning = bold + '(' + yellow + '!' + reset + bold + ')' + reset
		bullet = bold + '(' + lime + '*' + reset + bold + ')' + reset
		notice = bold + '(' + blue + '*' + reset + bold + ')' + reset
		ok = bold + '(' + lime + '>' + reset + bold + ')' + reset
		highlight = lime + bold
	# Glocal Print Functions
	def print_line(self, line, _verbose = False):
		""" Prints line with type"""
		global verbose
		if _verbose and not verbose:
			return
		print line
		return
		
	def print_table(self,list, _verbose = False, level = 0):
		""" Prints Lists of the form list[[a,b]]. Can be nested lists."""
		global verbose
		
		if _verbose and not verbose:
			return
		for item in list:
			if isinstance(item[0], basestring):
				print '  ',
				print(level * '  ' + space + item[0] + reset + '\r' + 3 * right + item[1])
			else:
				self.print_table(item, _verbose, level + 1)
		
	def print_exception(self, exception, iswarning = False):
		""" Prints Exceptions in a standart way """
		if iswarning:
			type = warning + ' Warning! '
		else:
			type = error + ' Error! '
		self.print_line('\n' + type + str(exception) + '\n')
	
	
	def format_action(self, action):
		table = []
		if action.type in ['sym','path']:
			table = self.format_options(action.options)
		elif action.type in ['runnable','env']:
			for line in action.usage:
				table.append([line,''])
		return table

	def format_options(self, options, counter = None):
		table = []
		for option in options:
			if isinstance(option, list) and not isinstance(option[0], int):
				sub = self.format_options(option)
				table.append(sub)
			else:
				table.append([str(option[0]) + ' - ' + option[1] + ' - ' + eval(option[2]),''])
		return table
		
	# Screen Functions
	
	# For debug			
	def print_nested(self, _list, level = 0):
		for item in _list:
			if isinstance(item, list):
				self.print_nested(item, level + 1)
			else:
				print level/2 * '*' + ' ' + str(item)
	
	def print_ui(self, module = None, modules = None, \
		action = None, args = None):
		if module == None:
			# uselect Usage
			# uselect Options
			self.print_usage()
			self.print_line('')
			self.print_options()
			self.print_line('')
			self.print_modules(modules)
			self.print_line('')
		elif action == None:
			# Modules Usage
			self.print_usage(module)
			self.print_line('')
			self.print_module(module)
			self.print_line('')
			# Modules Actions
			self.print_actions(module)
			self.print_line('')
		elif args == None:
			# Actions Usage
			self.print_usage(module, action)
			self.print_line('')
			# Action
			self.print_action(action)
			self.print_line('')
		else:
			# This means Action Done
			for line in action.output:
				print(line)
		return
	

			
	
	def print_module(self, module):
		self.print_line(highlight + space + 'Module' + space + reset \
		+ bold + module.name + lime + ':' + reset)
		self.print_line(space * 4 + bold + 'Author:' + reset + space + \
			module.author + space + bold + 'Version:' + reset + space \
			+ module.version)
			
	def print_modules(self, modules):
		self.print_line(highlight + space + 'Modules:' + reset)
		list = []
		for module in modules:
			list.append([bold + module.name, bullet + space + module.description])
		self.print_table(list)
		
	def print_actions(self, module):
		self.print_line(highlight + space + 'Actions:' + reset)
		if len(module.actions) == 0:
			print space * 4 + bold + '"' + module.name  + '"' + \
				' has no actions!'
			return
		list = []
		for action in module.actions:
			self.print_table([[bold + action.name + reset, \
				action.description]])
		
	def print_action(self, action):	
		self.print_table([[bold + action.description + reset, '']])
		self.print_line('')
		self.print_table(self.format_action(action))
			
	def print_version(self, version):
		self.print_line(bold + 'Universal Select Tool - ' \
			+ lime + 'uselect' + reset)
		self.print_line(bold + 'Version ' + reset + version + '\n')
		
	def print_usage(self, module = None, action = None):
		""" General Usage Printer """
		options = ''
		if module != None:
			module_name = module.name
		else:
			module_name = '<module>'
		if action != None:
			action_name = action.name
			for parameter in action.parameters:
				options += parameter + space
		else:
			action_name = '<action>'
			
		self.print_line(bold + lime + 'Usage:' + reset + ' uselect <options> ' + module_name \
		+ space + action_name + space + options)
		
	def print_options(self):
		
		self.print_line(highlight + space + 'Options:' + reset)
		table = [\
			[bold + '-v', bullet + space + 'Verbose Mode'], \
			[bold + '-nc', bullet + space + 'No Colors'], \
			[bold + '-version', bullet + space + 'Version Information']]
		if filesystem.uid == 'root':
			table.append([bold + '-global', bullet + space + 'Set Globally'])
		self.print_table(table)

	
class ProfilePrintSystem(PrintSystem):
	
	def print_ui(self, profile = None, profiles = None, args = None, \
		action = None, help = False, list = False):
		if profile == None:
			if help or list:
				self.print_usage(profile = profile, action = action)
				self.print_line('')
			if help:
				self.print_options()
				self.print_line('')
			if list:
				self.print_profiles(profiles)
				self.print_line('')
		elif profiles == None and action == None:
			self.print_usage(profile = profile, action = action)
			self.print_line('')
			self.print_profile(profile)
			self.print_line('')
			self.print_actions(profile)
			self.print_line('')
			
	def print_profiles(self, profiles):
		self.print_line(highlight + space + 'Profiles:' + reset)
		table = []
		if len(profiles) == 0:
			table.append([bold + 'No Profiles Found!' , ''])
		for profile in profiles:
			table.append([bold + profile.name, bullet + space + profile.description])
		self.print_table(table)

	def print_profile(self, profile):
		self.print_line(highlight + space + 'Profile' + space + reset \
			+ bold + profile.name + lime + ':' + reset)
		self.print_line(space * 4 + bold + 'Author:' + reset + space + \
			profile.author + space + bold + 'Version:' + reset + space \
			+ profile.version)
			
	def print_version(self, version):
		self.print_line(bold + 'Universal Profile Tool - ' \
			+ lime + 'uprofile' + reset)
		self.print_line(bold + 'Version ' + reset + version + '\n')
	
	def print_usage(self, profile = None, action = None):
		""" General Usage Printer """
		options = ''
		if profile != None:
			profile_name = profile.name
		else:
			profile_name = '<profile>'
		if action != None:
			action_name = action.name
			for parameter in action.parameters:
				options += parameter + space
		else:
			action_name = '<action>'
			
		self.print_line(bold + lime + 'Usage:' + reset + ' uprofile <options> ' + profile_name \
		+ space + action_name + space + options)
	
	def print_options(self):
		self.print_line(highlight + space + 'Options:' + reset)
		self.print_table([ \
			[bold + '-v', bullet + space + 'Verbose Mode'], \
			[bold + '-nc', bullet + space + 'No Colors'], \
			[bold + '-help', bullet + space + 'See this screen'], \
			[bold + '-list', bullet + space + 'List Profiles'], \
			[bold + '-version', bullet + space + 'Version Information']])
		self.print_line('')
		self.print_line(highlight + space + 'Usage Examples:' + reset)
		self.print_table([ \
			[bold + 'uprofile', bullet + space + 'Activates Folder Profile. Fallback to user profile.'], \
			[bold + 'uprofile <profile>', bullet + space + 'See Details on <profile>']])
		
filesystem = FileSystem()
printsystem = PrintSystem()