~romaimperator/keryx/devel

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
#!/usr/bin/env python

""" Keryx executable """

__appname__   = 'keryx'
__version__   = '1.0.0'
__supports__  = '0'
__author__    = 'Buran Ayuthia'


import logging
import os
from sys import argv, exit
from optparse import OptionParser, OptionGroup
import libkeryx


"""
    * 1 apt-get commands     (For 1.0)
          o 1.1 keryx update
          o 1.3 keryx download some-package
          o 1.5 keryx remove some-package
          o 1.6 keryx apt-clean
          o 1.7 keryx clean
    * 2 apt-cache commands   (For 1.0)
          o 2.3 keryx showpkg
          o 2.4 keryx stats
          o 2.5 keryx dump
          o 2.7 keryx unmet
          o 2.9 keryx search
          o 2.10 keryx show
          o 2.11 keryx depends
          o 2.12 keryx pkgnames

    * 1 apt-get commands     (For future)
          o 1.2 keryx install some-package
          o 1.4 keryx dist-upgrade
          o 1.6 keryx apt-clean
          o 1.7 keryx clean
    * 2 apt-cache commands   (For future)
          o 2.1 keryx add
          o 2.2 keryx gencaches
          o 2.6 keryx dumpavail
          o 2.8 keryx check
          o 2.13 keryx dotty
"""


FORMAT = '%(asctime)s %(levelname)-8s %(message)s'
DATE = '%a, %d %b %Y %H:%M:%S'
db_filename = os.path.join(os.path.dirname(__file__), 'keryx.db')


class Keryx:
    def __init__(self):
        self.command = ''
        self.project = ''
        self.wx_gui = False


    def __parse_command(self, command):
        pass


    def parse_options(self, args):
        command_list = ['create', 'update', 'download', 'remove', \
                        'clean', 'showpkg', 'dump', 'unmet', 'search', \
                        'show', 'depends', 'pkgnames']
        usage = 'usage: %prog project command [options]\n\n' \
                'Actions (if none is specified, Keryx will enter ' \
                'GUI mode):'
        version = __version__
        description = 'create   - Create a new project      ' \
                      '                                     ' \
                      'update   - Get updated package list from the ' \
                      'Internet                                     ' \
                      'download - Download selected packages for ' \
                      'the project                               ' \
                      'remove   - Removes a package from the download ' \
                      'list                                           ' \
                      'clean    - Removes all the packages from the ' \
                      'download list                                ' \
                      'showpkg  - Display general information for a ' \
                      'package                                      ' \
                      'search   - Display packages that match the ' \
                      'search string                              ' \
                      'show     - Display information about a ' \
                      'particular package                     ' \
                      'depends  - Display the dependencies for a ' \
                      'particular package                        ' \
                      'pkgnames - List the names of all the packages'
        parser = OptionParser(usage, description=description, version=version)  

        download_group = OptionGroup(parser, 'Download')
        download_group.add_option('-D', '--download', action='store_true', \
            dest='download', \
            help='Download only - do NOT install or unpack archives')
        download_group.add_option('-s', '--simulate', action='store_true', 
            dest='simulate', help='No-act. Perform ordering simulation')
        download_group.add_option('-y', '--yes', action='store_true', \
            dest='auto_yes', \
            help='Assume Yes to all queries and do not prompt')
        download_group.add_option('-u', '--show-upgrades', \
            action='store_true', dest='upgrades', \
            help='Show a list of upgraded packages as well')

        parser.add_option_group(download_group)
#       Not an option for 1.0
#        parser.add_option('-f', '--force', action='store_true', \
#            dest='force', \
#            help='Attempt to continue if the integrity check fails')



        (options, arguments) = parser.parse_args(args)

        # Configure verbosity
        #TODO: Fix it so basicConfig works
        logging.basicConfig()
        logging.root.setLevel(logging.DEBUG)

        if len(arguments) == 1:
            self.wx_gui = True
            
        if len(arguments) < 2:
            parser.error('Missing the project name')
        
        if len(arguments) > 2:
            self.command = None
            if argv[2] not in command_list:
                print('Unknown command \'%s\'' % args[2])
                # The following is used to remove the None at the end
                # of the parser.print_help data
                help_msg = str(parser.print_help())
                help_msg = help_msg.split('\n')
                for index in range(len(help_msg) - 2):
                    print help_msg[index]
                exit(1)
            else:
                self.command = args[2]
        
        self.project = args[1]


    def execute(self):
        if self.wx_gui:
            print 'call GUI version'
            # If GUI fails, launch KeryxCLI
            cli = KeryxCLI(self.project)
            cli.main()
        else:
            if not self.command:
                cli = KeryxCLI(self.project)
                cli.main()
            if self.command == 'create':
                definition = libkeryx.get_definition(self.project, db_filename)
                definition.Create()
            if self.command == 'update':
                definition = libkeryx.get_definition(self.project, db_filename)
                definition.Update()


class KeryxCLI():
    """Keryx Interactive CLI"""
    help = """
Commands:
open <project name>
create - Creates the current project into database
update - Updates the current project
"""
    
    def __init__(self, name):
        """Set project for CLI usage"""
        self.set_project(name)
        
        
    def set_project(self, name):
        """Sets project to name"""
        self.name = name
        self.project = libkeryx.get_definition(name, db_filename)
        # Check self.project.Verify() and notify user if project is not created


    def main(self):
        """Main loop for Keryx interactive CLI"""
        #Dictionary of commands and there function call second parameter
        #       boolean is true if the command takes arguments
        commands = {"create" : ["Create", False],
                    "update" : ["Update", False],
                    "upgrade" : ["Upgrade", False], 
                    #"download" : ["Download", True],
                    #"remove" : ["Remove",  True], 
                    #"apt-clean" : ["AptClean", False],
                    #"clean" : ["Clean", False], 
                    #"showpkg" : ["ShowPkg", False], 
                    #"stats" : ["Stats", False], 
                    #"dump" : ["Dump", False], 
                    #"unmet" : ["Unmet", True], 
                    #"search" : ["Search", True], 
                    #"show" : ["Show", True], 
                    #"depends" : ["Depends", True], 
                    #"pkgnames" : ["PkgNames", False]
                    }
        
        if os.system("clear") != 0:
            os.system("cls")
        print "\nKeryx %s Interactive Command Line Interface\n" % __version__
        
        input = [""]
        while input[0] != "exit":
            prompt = "%s:%s>" % (__appname__, self.name)
            input = raw_input(prompt).strip().split()
            if input:
                input = [x.lower() for x in input]
                if commands.has_key(input[0]):
                    x = getattr(self.project, commands[input[0]][0])
                    if commands[input[0]][1]:
                        x(input[1:])
                    else:
                        x()
                else:
                    if input[0] == "help":
                        print self.help
                    elif input[0] == "exit":
                        pass
#                if command[0] == "open":
#                    if len(command) > 1:
#                        name = command[1].strip()
#                        self.set_project(name)
#                    else:
#                        print self.help
                    else:
                        print "Command not found. Type 'help' for details."
            else:
                # No command input
                command = [""]
                        

# keryx <project-name> <command(s)> <option(s)>
if __name__ == '__main__':
    keryx = Keryx()
    no_errors = keryx.parse_options(argv)
    keryx.execute()