File: cli.py

package info (click to toggle)
yum 2.4.0-3.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,252 kB
  • ctags: 1,149
  • sloc: python: 11,641; makefile: 155; sh: 55
file content (1544 lines) | stat: -rw-r--r-- 61,956 bytes parent folder | download
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
#!/usr/bin/python -t
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Copyright 2005 Duke University 
# Written by Seth Vidal


import os
import os.path
import sys
import time
import random
import fcntl
import fnmatch
import re
from optparse import OptionParser

import output
import shell
import yum
import yum.Errors
import yum.misc
import rpmUtils.arch
from rpmUtils.miscutils import compareEVR
from yum.packages import parsePackages, returnBestPackages, YumInstalledPackage, YumLocalPackage
from yum.logger import Logger
from yum.config import yumconf
from yum import pgpmsg
from i18n import _
import callback
import urlgrabber
import urlgrabber.grabber

class CliError(yum.Errors.YumBaseError):
   def __init__(self, args=None):
        yum.Errors.YumBaseError.__init__(self)
        self.args = args

class YumBaseCli(yum.YumBase, output.YumOutput):
    """This is the base class for yum cli.
       Inherits from yum.YumBase and output.YumOutput """
       
    def __init__(self):
        yum.YumBase.__init__(self)
        self.localPackages = [] # for local package handling - possibly needs
                                # to move to the lower level class

    def doRepoSetup(self, thisrepo=None, dosack=1):
        """grabs the repomd.xml for each enabled repository 
           and sets up the basics of the repository"""
        
        if hasattr(self, 'pkgSack') and thisrepo is None:
            self.log(7, 'skipping reposetup, pkgsack exists')
            return
            
        self.log(2, 'Setting up repositories')

        # Call parent class to do the bulk of work 
        # (this also ensures that reposetup plugin hook is called)
        yum.YumBase.doRepoSetup(self, thisrepo=thisrepo)

        if dosack: # so we can make the dirs and grab the repomd.xml but not import the md
            self.log(2, 'Reading repository metadata in from local files')
            self.doSackSetup(thisrepo=thisrepo)
    
        
    def getOptionsConfig(self, args):
        """parses command line arguments, takes cli args:
        sets up self.conf and self.cmds as well as logger objects 
        in base instance"""
        
        # setup our errorlog object 
        self.errorlog = Logger(threshold=2, file_object=sys.stderr)
    
        def repo_optcb(optobj, opt, value, parser):
            '''Callback for the enablerepo and disablerepo option. 
            
            Combines the values given for these options while preserving order
            from command line.
            '''
            dest = eval('parser.values.%s' % optobj.dest)
            dest.append((opt, value))

        self.optparser = YumOptionParser(base=self, usage='''\
yum [options] < update | install | info | remove | list |
    clean | provides | search | check-update | groupinstall | 
    groupupdate | grouplist | groupinfo | groupremove |
    makecache | localinstall | erase | upgrade | whatprovides |
    localupdate | resolvedep | shell | deplist >''')

        self.optparser.add_option("-t", "--tolerant", dest="tolerant",
                action="store_true", default=False, help="be tolerant of errors")
        self.optparser.add_option("-C", "", dest="cacheonly",
                action="store_true", default=False, 
                help="run entirely from cache, don't update cache")
        self.optparser.add_option("-c", "", dest="conffile", action="store", 
                default='/etc/yum.conf', help="config file location", 
                metavar=' [config file]')
        self.optparser.add_option("-R", "", dest="sleeptime", action="store", 
                type='int', default=None, help="maximum command wait time",
                metavar=' [minutes]')
        self.optparser.add_option("-d", "", dest="debuglevel", action="store", 
                default=None, help="debugging output level", type='int',
                metavar=' [debug level]')
        self.optparser.add_option("-e", "", dest="errorlevel", action="store", 
                default=None, help="error output level", type='int',
                metavar=' [error level]')
        self.optparser.add_option("-y", "", dest="assumeyes",
                action="store_true", default=False, 
                help="answer yes for all questions")
        self.optparser.add_option("", "--version", dest="version",
                default=False, action="store_true", 
                help="show Yum version and exit")
        self.optparser.add_option("", "--installroot", dest="installroot",
                action="store", default=None, help="set install root", 
                metavar='[path]')
        self.optparser.add_option("", "--enablerepo", action='callback',
                type='string', callback=repo_optcb, dest='repos', default=[],
                help="enable one or more repositories (wildcards allowed)",
                metavar='[repo]')
        self.optparser.add_option("", "--disablerepo", action='callback',
                type='string', callback=repo_optcb, dest='repos', default=[],
                help="disable one or more repositories (wildcards allowed)",
                metavar='[repo]')
        self.optparser.add_option("", "--exclude", dest="exclude", default=[], 
                action="append", help="exclude package(s) by name or glob",
                metavar='[package]')
        self.optparser.add_option("", "--obsoletes", dest="obsoletes",
                default=False, action="store_true", 
                help="enable obsoletes processing during updates")
        self.optparser.add_option("", "--noplugins", dest="noplugins",
                default=False, action="store_true", 
                help="disable Yum plugins")
        
        # Parse only command line options that affect basic yum setup
        try:
            args = _filtercmdline(
                        ('--noplugins',), 
                        ('-c', '-d', '-e', '--installroot'), 
                        args,
                    )
        except ValueError:
            self.usage()
            sys.exit(1)
        opts = self.optparser.parse_args(args=args)[0]

        try: 
            # If the conf file is inside the  installroot - use that.
            # otherwise look for it in the normal root
            if opts.installroot:
                if os.access(opts.installroot+'/'+opts.conffile, os.R_OK):
                    opts.conffile = opts.installroot+'/'+opts.conffile
                root=opts.installroot
            else:
                root = '/'
                    
            # Parse the configuration file
            try:
                self.doConfigSetup(fn=opts.conffile, root=root)
            except yum.Errors.ConfigError, e:
                self.errorlog(0, _('Config Error: %s') % e)
                sys.exit(1)
                
            # Initialise logger object
            self.log=Logger(threshold=self.conf.getConfigOption('debuglevel'), 
                    file_object=sys.stdout)

            # Setup debug and error levels
            if opts.debuglevel is not None:
                self.log.threshold=opts.debuglevel
                self.conf.setConfigOption('debuglevel', opts.debuglevel)

            if opts.errorlevel is not None:
                self.errorlog.threshold=opts.errorlevel
                self.conf.setConfigOption('errorlevel', opts.errorlevel)

        except ValueError, e:
            self.errorlog(0, _('Options Error: %s') % e)
            self.usage()
            sys.exit(1)

        # Initialise plugins if cmd line and config file say these should be in
        # use (this may add extra command line options)
        if not opts.noplugins and self.conf.plugins:
            self.doPluginSetup(self.optparser)

        # Now parse the command line for real
        (opts, self.cmds) = self.optparser.parse_args()

        # Just print out the version if that's what the user wanted
        if opts.version:
            print yum.__version__
            sys.exit(0)

        # Let the plugins know what happened on the command line
        self.plugins.setCmdLine(opts, self.cmds)

        try:
            # config file is parsed and moving us forward
            # set some things in it.
                
            # who are we:
            self.conf.setConfigOption('uid', os.geteuid())

            # version of yum
            self.conf.setConfigOption('yumversion', yum.__version__)
            
            # syslog-style log
            if self.conf.getConfigOption('uid') == 0:
                logpath = os.path.dirname(self.conf.logfile)
                if not os.path.exists(logpath):
                    try:
                        os.makedirs(logpath, mode=0755)
                    except OSError, e:
                        self.errorlog(0, _('Cannot make directory for logfile %s' % logpath))
                        sys.exit(1)
                try:
                    logfd = os.open(self.conf.logfile, os.O_WRONLY |
                                    os.O_APPEND | os.O_CREAT, 0644)
                except OSError, e:
                    self.errorlog(0, _('Cannot open logfile %s' % self.conf.logfile))
                    sys.exit(1)

                logfile =  os.fdopen(logfd, 'a')
                fcntl.fcntl(logfd, fcntl.F_SETFD)
                self.filelog = Logger(threshold = 10, file_object = logfile, 
                                preprefix = self.printtime)
            else:
                self.filelog = Logger(threshold = 10, file_object = None, 
                                preprefix = self.printtime)
            
            # Handle remaining options
            if opts.assumeyes:
                self.conf.setConfigOption('assumeyes',1)

            if opts.cacheonly:
                self.conf.setConfigOption('cache', 1)

            if opts.sleeptime is not None:
                sleeptime = random.randrange(opts.sleeptime*60)
            else:
                sleeptime = 0

            if opts.obsoletes:
                self.conf.setConfigOption('obsoletes', 1)

            if opts.installroot:
                self.conf.setConfigOption('installroot', opts.installroot)

            for exclude in opts.exclude:
                try:
                    excludelist = self.conf.getConfigOption('exclude')
                    excludelist.append(exclude)
                    self.conf.setConfigOption('exclude', excludelist)
                except yum.Errors.ConfigError, e:
                    self.errorlog(0, _(e))
                    self.usage()
                    sys.exit(1)
               
            # Process repo enables and disables in order
            for opt, repoexp in opts.repos:
                try:
                    if opt == '--enablerepo':
                        self.repos.enableRepo(repoexp)
                    elif opt == '--disablerepo':
                        self.repos.disableRepo(repoexp)
                except yum.Errors.ConfigError, e:
                    self.errorlog(0, _(e))
                    self.usage()
                    sys.exit(1)
                            
        except ValueError, e:
            self.errorlog(0, _('Options Error: %s') % e)
            self.usage()
            sys.exit(1)
         
        # setup the progress bars/callbacks
        self.setupProgessCallbacks()
        
        # save our original args out
        self.args = args
        # save out as a nice command string
        self.cmdstring = 'yum '
        for arg in self.args:
            self.cmdstring += '%s ' % arg

        try:
            self.parseCommands() # before we return check over the base command + args
                                 # make sure they match/make sense
        except CliError:
            sys.exit(1)
    
        # set our caching mode correctly
        
        if self.conf.getConfigOption('uid') != 0:
            self.conf.setConfigOption('cache', 1)
        # run the sleep - if it's unchanged then it won't matter
        time.sleep(sleeptime)


    def parseCommands(self, mycommands=[]):
        """reads self.cmds and parses them out to make sure that the requested 
        base command + argument makes any sense at all""" 

        self.log(3, 'Yum Version: %s' % self.conf.getConfigOption('yumversion'))
        self.log(3, 'COMMAND: %s' % self.cmdstring)
        self.log(3, 'Installroot: %s' % self.conf.getConfigOption('installroot'))
        if len(self.conf.getConfigOption('commands')) == 0 and len(self.cmds) < 1:
            self.cmds = self.conf.getConfigOption('commands')
        else:
            self.conf.setConfigOption('commands', self.cmds)
        if len(self.cmds) < 1:
            self.errorlog(0, _('You need to give some command'))
            self.usage()
            raise CliError
            
        self.basecmd = self.cmds[0] # our base command
        self.extcmds = self.cmds[1:] # out extended arguments/commands
        
        if len(self.extcmds) > 0:
            self.log(3, 'Ext Commands:\n')
            for arg in self.extcmds:
                self.log(3, '   %s' % arg)
        
        if self.basecmd not in ['update', 'install','info', 'list', 'erase',
                                'grouplist', 'groupupdate', 'groupinstall',
                                'groupremove', 'groupinfo', 'makecache',
                                'clean', 'remove', 'provides', 'check-update',
                                'search', 'upgrade', 'whatprovides',
                                'localinstall', 'localupdate',
                                'resolvedep', 'shell', 'deplist']:
            self.usage()
            raise CliError
    
        if self.conf.getConfigOption('uid') != 0:
            if self.basecmd in ['install', 'update', 'clean', 'upgrade','erase', 
                                'groupupdate', 'groupinstall', 'remove',
                                'groupremove', 'importkey', 'makecache', 
                                'localinstall', 'localupdate']:
                self.errorlog(0, _('You need to be root to perform this command.'))
                raise CliError

        if self.basecmd in ['install', 'update', 'upgrade', 'groupinstall',
                            'groupupdate', 'localinstall', 'localupdate']:

            if not self.gpgKeyCheck():
                for repo in self.repos.listEnabled():
                    if repo.gpgcheck and repo.gpgkey == '':
                        msg = _("""
You have enabled checking of packages via GPG keys. This is a good thing. 
However, you do not have any GPG public keys installed. You need to download
the keys for packages you wish to install and install them.
You can do that by running the command:
    rpm --import public.gpg.key


Alternatively you can specify the url to the key you would like to use
for a repository in the 'gpgkey' option in a repository section and yum 
will install it for you.

For more information contact your distribution or package provider.
""")
                        self.errorlog(0, msg)
                        raise CliError

                
        if self.basecmd in ['install', 'erase', 'remove', 'localinstall', 'localupdate', 'deplist']:
            if len(self.extcmds) == 0:
                self.errorlog(0, _('Error: Need to pass a list of pkgs to %s') % self.basecmd)
                self.usage()
                raise CliError
    
        elif self.basecmd in ['provides', 'search', 'whatprovides']:
            if len(self.extcmds) == 0:
                self.errorlog(0, _('Error: Need an item to match'))
                self.usage()
                raise CliError
                
        elif self.basecmd in ['groupupdate', 'groupinstall', 'groupremove', 'groupinfo']:
            if len(self.extcmds) == 0:
                self.errorlog(0, _('Error: Need a group or list of groups'))
                self.usage()
                raise CliError
                
        elif self.basecmd == 'clean':
            if len(self.extcmds) == 0:
                self.errorlog(0,
                    _('Error: clean requires an option: headers, packages, cache, metadata, all'))
            for cmd in self.extcmds:
                if cmd not in ['headers', 'packages', 'metadata', 'cache', 'dbcache', 'all']:
                    self.usage()
                    raise CliError
                    
        elif self.basecmd == 'shell':
            if len(self.extcmds) == 0:
                self.log(3, "No argument to shell")
                pass
            elif len(self.extcmds) == 1:
                self.log(3, "Filename passed to shell: %s" % self.extcmds[0])              
                if not os.path.isfile(self.extcmds[0]):
                    self.errorlog(
                        0, _("File: %s given has argument to shell does not exists." % self.extcmds))
                    self.usage()
                    raise CliError
            else:
                self.errorlog(0,_("Error: more than one file given as argument to shell."))
                self.usage()
                raise CliError
              
        elif self.basecmd in ['list', 'check-update', 'info', 'update', 'upgrade',
                              'grouplist', 'makecache', 'resolvedep']:
            pass
    
        else:
            self.usage()
            raise CliError


    def doShell(self):
        """do a shell-like interface for yum commands"""

        self.log(2, 'Setting up Yum Shell')
        self.doTsSetup()
        self.doRpmDBSetup()
        if len(self.extcmds) == 0:
            yumshell = shell.YumShell(base=self)
            yumshell.cmdloop()
        else:
            yumshell = shell.YumShell(base=self)
            yumshell.script()
        return yumshell.result, yumshell.resultmsgs

    def doCommands(self):
        """calls the base command passes the extended commands/args out to be
        parsed. (most notably package globs). returns a numeric result code and
        an optional string
           0 = we're done, exit
           1 = we've errored, exit with error string
           2 = we've got work yet to do, onto the next stage"""
        
        # at this point we know the args are valid - we don't know their meaning
        # but we know we're not being sent garbage
        
        # setup our transaction sets (needed globally, here's a good a place as any)
        try:
            self.doTsSetup()
        except yum.Errors.YumBaseError, e:
            return 1, [str(e)]
        
        if self.basecmd == 'install':
            self.log(2, "Setting up Install Process")
            try:
                return self.installPkgs()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
        
        elif self.basecmd == 'update':
            self.log(2, "Setting up Update Process")
            try:
                return self.updatePkgs()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]

            
        elif self.basecmd == 'upgrade':
            self.conf.setConfigOption('obsoletes', 1)
            self.log(2, "Setting up Upgrade Process")
            try:
                return self.updatePkgs()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
            
            
        elif self.basecmd in ['erase', 'remove']:
            self.log(2, "Setting up Remove Process")
            try:
                return self.erasePkgs()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
            

        elif self.basecmd in ['localinstall', 'localupdate']:
            self.log(2, "Setting up Local Package Process")
            updateonly=0
            if self.basecmd == 'localupdate': updateonly=1
                
            try:
                return self.localInstall(updateonly=updateonly)
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]

            
        elif self.basecmd in ['list', 'info']:
            try:
                ypl = self.returnPkgLists()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
            else:
                self.listPkgs(ypl.installed, 'Installed Packages', self.basecmd)
                self.listPkgs(ypl.available, 'Available Packages', self.basecmd)
                self.listPkgs(ypl.extras, 'Extra Packages', self.basecmd)
                self.listPkgs(ypl.updates, 'Updated Packages', self.basecmd)
                if len(ypl.obsoletes) > 0 and self.basecmd == 'list': 
                # if we've looked up obsolete lists and it's a list request
                    print 'Obsoleting Packages'
                    for obtup in ypl.obsoletesTuples:
                        self.updatesObsoletesList(obtup, 'obsoletes')
                else:
                    self.listPkgs(ypl.obsoletes, 'Obsoleting Packages', self.basecmd)
                self.listPkgs(ypl.recent, 'Recently Added Packages', self.basecmd)
                return 0, []

        elif self.basecmd == 'check-update':
            self.extcmds.insert(0, 'updates')
            result = 0
            try:
                ypl = self.returnPkgLists()
                if len(ypl.updates) > 0:
                    self.listPkgs(ypl.updates, '', outputType='list')
                    result = 100
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
            else:
                return result, []
            
        elif self.basecmd in ['deplist']:
           self.log(2, "Finding dependencies: ")
           try:
              return self.deplist()
           except yum.Errors.YumBaseError, e:
              return 1, [str(e)]

        elif self.basecmd == 'clean':
            self.conf.setConfigOption('cache', 1)
            return self.cleanCli()
        
        elif self.basecmd in ['groupupdate', 'groupinstall', 'groupremove', 
                              'grouplist', 'groupinfo']:

            self.log(2, "Setting up Group Process")

            self.doRepoSetup(dosack=0)
            try:
                self.doGroupSetup()
            except yum.Errors.GroupsError:
                return 1, ['No Groups on which to run command']
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
            
            if self.basecmd == 'grouplist':
                return self.returnGroupLists()
            
            elif self.basecmd == 'groupinstall':
                try:
                    return self.installGroups()
                except yum.Errors.YumBaseError, e:
                    return 1, [str(e)]
            
            elif self.basecmd == 'groupupdate':
                try:
                    return self.updateGroups()
                except yum.Errors.YumBaseError, e:
                    return 1, [str(e)]
            
            elif self.basecmd == 'groupremove':
                try:
                    return self.removeGroups()
                except yum.Errors.YumBaseError, e:
                    return 1, [str(e)]
            elif self.basecmd == 'groupinfo':
                try:
                    return self.returnGroupInfo()
                except yum.Errors.YumBaseError, e:
                    return 1, [str(e)]
            
        elif self.basecmd in ['search']:
            self.log(2, "Searching Packages: ")
            try:
                return self.search()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
        
        elif self.basecmd in ['provides', 'whatprovides']:
            self.log(2, "Searching Packages: ")
            try:
                return self.provides()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]

        elif self.basecmd in ['resolvedep']:
            self.log(2, "Searching Packages for Dependency:")
            try:
                return self.resolveDepCli()
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
        
        elif self.basecmd in ['makecache']:
            self.log(2, "Making cache files for all metadata files.")
            self.log(2, "This may take a while depending on the speed of this computer")
            self.log(3, '%s' % self.pickleRecipe())
            try:
                self.doRepoSetup(dosack=0)
                self.repos.populateSack(with='metadata', pickleonly=1)
                self.repos.populateSack(with='filelists', pickleonly=1)
                self.repos.populateSack(with='otherdata', pickleonly=1)
                
            except yum.Errors.YumBaseError, e:
                return 1, [str(e)]
            return 0, ['Metadata Cache Created']
            
        else:
            return 1, ['command not implemented/not found']

    def doTransaction(self):
        """takes care of package downloading, checking, user confirmation and actually
           RUNNING the transaction"""

        # output what will be done:
        self.log(1, self.listTransaction())
        
        # Check which packages have to be downloaded
        downloadpkgs = []
        for txmbr in self.tsInfo.getMembers():
            if txmbr.ts_state in ['i', 'u']:
                po = txmbr.po
                if po:
                    downloadpkgs.append(po)

        # Report the total download size to the user, so he/she can base
        # the answer on this info
        self.reportDownloadSize(downloadpkgs)
        
        # confirm with user
        if self._promptWanted():
            if not self.userconfirm():
                self.log(0, 'Exiting on user Command')
                return 1

        self.log(2, 'Downloading Packages:')
        problems = self.downloadPkgs(downloadpkgs) 

        if len(problems.keys()) > 0:
            errstring = ''
            errstring += 'Error Downloading Packages:\n'
            for key in problems.keys():
                errors = yum.misc.unique(problems[key])
                for error in errors:
                    errstring += '  %s: %s\n' % (key, error)
            raise yum.Errors.YumBaseError, errstring

        # Check GPG signatures
        if self.gpgsigcheck(downloadpkgs) != 0:
            return 1
        
        self.log(2, 'Running Transaction Test')
        tsConf = {}
        for feature in ['diskspacecheck']: # more to come, I'm sure
            tsConf[feature] = self.conf.getConfigOption(feature)
        
        testcb = callback.RPMInstallCallback(output=0)
        testcb.tsInfo = self.tsInfo
        # clean out the ts b/c we have to give it new paths to the rpms 
        del self.ts
        
        self.initActionTs()
        # save our dsCallback out
        dscb = self.dsCallback
        self.dsCallback = None # dumb, dumb dumb dumb!
        self.populateTs(keepold=0) # sigh
        tserrors = self.ts.test(testcb, conf=tsConf)
        del testcb
        
        self.log(2, 'Finished Transaction Test')
        if len(tserrors) > 0:
            errstring = 'Transaction Check Error: '
            for descr in tserrors:
                errstring += '  %s\n' % descr 
            
            raise yum.Errors.YumBaseError, errstring
        self.log(2, 'Transaction Test Succeeded')
        del self.ts
        
        self.initActionTs() # make a new, blank ts to populate
        self.populateTs(keepold=0) # populate the ts
        self.ts.check() #required for ordering
        self.ts.order() # order

        # put back our depcheck callback
        self.dsCallback = dscb

        output = 1
        if self.conf.debuglevel < 2:
            output = 0
        cb = callback.RPMInstallCallback(output=output)
        cb.filelog = self.filelog # needed for log file output
        cb.tsInfo = self.tsInfo

        self.log(2, 'Running Transaction')
        self.runTransaction(cb=cb)

        # close things
        self.log(1, self.postTransactionOutput())
        return 0
        
    def gpgsigcheck(self, pkgs):
        '''Perform GPG signature verification on the given packages, installing
        keys if possible

        Returns non-zero if execution should stop (user abort).
        Will raise YumBaseError if there's a problem
        '''
        for po in pkgs:
            result, errmsg = self.sigCheckPkg(po)

            if result == 0:
                # Verified ok, or verify not req'd
                continue            

            elif result == 1:
                # Key needs to be installed
                self.log(0, errmsg)
    
                # Bail if not -y and stdin isn't a tty as key import will
                # require user confirmation
                if not sys.stdin.isatty() and not \
                            self.conf.getConfigOption('assumeyes'):
                    raise yum.Errors.YumBaseError, \
                        'Refusing to automatically import keys when running ' \
                        'unattended.\nUse "-y" to override.'

                repo = self.repos.getRepo(po.repoid)
                keyurls = repo.gpgkey
                key_installed = False

                for keyurl in keyurls:
                    self.log(0, 'Retrieving GPG key from %s' % keyurl)

                    # Go get the GPG key from the given URL
                    try:
                        rawkey = urlgrabber.urlread(keyurl, limit=9999)
                    except urlgrabber.grabber.URLGrabError, e:
                        raise yum.Errors.YumBaseError(
                                'GPG key retrieval failed: ' + str(e))

                    # Parse the key
                    try:
                        keyinfo = yum.misc.getgpgkeyinfo(rawkey)
                        keyid = keyinfo['keyid']
                        hexkeyid = yum.misc.keyIdToRPMVer(keyid).upper()
                        timestamp = keyinfo['timestamp']
                        userid = keyinfo['userid']
                    except ValueError, e:
                        raise yum.Errors.YumBaseError, \
                                'GPG key parsing failed: ' + str(e)

                    # Check if key is already installed
                    if yum.misc.keyInstalled(self.read_ts, keyid, timestamp) >= 0:
                        self.log(0, 'GPG key at %s (0x%s) is already installed' % (
                                keyurl,
                                hexkeyid
                                ))
                        continue

                    # Try installing/updating GPG key
                    self.log(0, 'Importing GPG key 0x%s "%s"' % (hexkeyid, userid))
                    if not self.conf.getConfigOption('assumeyes'):
                        if not self.userconfirm():
                            self.log(0, 'Exiting on user command')
                            return 1
            
                    # Import the key
                    result = self.ts.pgpImportPubkey(yum.misc.procgpgkey(rawkey))
                    if result != 0:
                        raise yum.Errors.YumBaseError, \
                                'Key import failed (code %d)' % result
                    self.log(1, 'Key imported successfully')
                    key_installed = True

                if not key_installed:
                    raise yum.Errors.YumBaseError, \
                        'The GPG keys listed for the "%s" repository are ' \
                        'already installed but they are not correct for this ' \
                        'package.\n' \
                        'Check that the correct key URLs are configured for ' \
                        'this repository.' % (repo.name)

                # Check if the newly installed keys helped
                result, errmsg = self.sigCheckPkg(po)
                if result != 0:
                    self.log(0, "Import of key(s) didn't help, wrong key(s)?")
                    raise yum.Errors.YumBaseError, errmsg

            else:
                # Fatal error
                raise yum.Errors.YumBaseError, errmsg

        return 0

    
    def installPkgs(self, userlist=None):
        """Attempts to take the user specified list of packages/wildcards
           and install them, or if they are installed, update them to a newer
           version. If a complete version number if specified, attempt to 
           downgrade them to the specified version"""
        # get the list of available packages
        # iterate over the user's list
        # add packages to Transaction holding class if they match.
        # if we've added any packages to the transaction then return 2 and a string
        # if we've hit a snag, return 1 and the failure explanation
        # if we've got nothing to do, return 0 and a 'nothing available to install' string
        
        oldcount = len(self.tsInfo)
        
        if not userlist:
            userlist = self.extcmds

        self.doRepoSetup()
        self.doRpmDBSetup()
        installed = self.rpmdb.getPkgList()
        avail = self.pkgSack.returnPackages()
        toBeInstalled = {} # keyed on name
        passToUpdate = [] # list of pkgtups to pass along to updatecheck

        self.log(2, _('Parsing package install arguments'))
        for arg in userlist:
            if os.path.exists(arg) and arg.endswith('.rpm'): # this is hurky, deal w/it
                val, msglist = self.localInstall(filelist=[arg])
                continue # it was something on disk and it ended in rpm 
                         # no matter what we don't go looking at repos

            arglist = [arg]
            exactmatch, matched, unmatched = parsePackages(avail, arglist, 
                                                               casematch=1)
            if len(unmatched) > 0: # if we get back anything in unmatched, check it for a virtual-provide
                arg = unmatched[0] #only one in there
                self.log(3, 'Checking for virtual provide or file-provide for %s' % arg)
                try:
                    mypkg = self.returnPackageByDep(arg)
                except yum.Errors.YumBaseError, e:
                    self.errorlog(0, _('No Match for argument: %s') % arg)
                else:
                    arg = '%s:%s-%s-%s.%s' % (mypkg.epoch, mypkg.name,
                                              mypkg.version, mypkg.release,
                                              mypkg.arch)
                    emtch, mtch, unmtch = parsePackages(avail, [arg])
                    exactmatch.extend(emtch)
                    matched.extend(mtch)
            
            installable = yum.misc.unique(exactmatch + matched)
            exactarchlist = self.conf.exactarchlist
            
            # we look through each returned possibility and rule out the
            # ones that we obviously can't use
            for pkg in installable:
                if pkg.pkgtup in installed:
                    self.log(6, 'Package %s is already installed, skipping' % pkg)
                    continue
                
                # everything installed that matches the name
                installedByKey = self.rpmdb.returnTupleByKeyword(name=pkg.name)
                comparable = []
                for instTup in installedByKey:
                    (n2, a2, e2, v2, r2) = instTup
                    if rpmUtils.arch.isMultiLibArch(a2) == rpmUtils.arch.isMultiLibArch(pkg.arch):
                        comparable.append(instTup)
                    else:
                        self.log(6, 'Discarding non-comparable pkg %s.%s' % (n2, a2))
                        continue
                        
                # go through each package 
                if len(comparable) > 0:
                    for instTup in comparable:
                        (n2, a2, e2, v2, r2) = instTup
                        rc = compareEVR((e2, v2, r2), (pkg.epoch, pkg.version, pkg.release))
                        if rc < 0: # we're newer - this is an update, pass to them
                            if n2 in exactarchlist:
                                if pkg.arch == a2:
                                    passToUpdate.append(pkg.pkgtup)
                            else:
                                passToUpdate.append(pkg.pkgtup)
                        elif rc == 0: # same, ignore
                            continue
                        elif rc > 0: # lesser, check if the pkgtup is an exactmatch
                                        # if so then add it to be installed,
                                        # the user explicitly wants this version
                                        # FIXME this is untrue if the exactmatch
                                        # does not include a version-rel section
                            if pkg.pkgtup in exactmatch:
                                if not toBeInstalled.has_key(pkg.name): toBeInstalled[pkg.name] = []
                                toBeInstalled[pkg.name].append(pkg.pkgtup)
                else: # we've not got any installed that match n or n+a
                    self.log(4, 'No other %s installed, adding to list for potential install' % pkg.name)
                    if not toBeInstalled.has_key(pkg.name): toBeInstalled[pkg.name] = []
                    toBeInstalled[pkg.name].append(pkg.pkgtup)
        
        
        # this is where I could catch the installs of compat and multilib 
        # arches on a single yum install command. 
        pkglist = returnBestPackages(toBeInstalled)
        
        # This is where we need to do a lookup to find out if this install
        # is also an obsolete. if so then we need to mark it as such in the
        # tsInfo.
        if len(pkglist) > 0:
            self.log(3, 'reduced installs :')
        for pkgtup in pkglist:
            self.log(3,'   %s.%s %s:%s-%s' % pkgtup)
            po = self.getPackageObject(pkgtup)
            self.tsInfo.addInstall(po)

        if len(passToUpdate) > 0:
            self.log(3, 'potential updates :')
            updatelist = []
            for (n,a,e,v,r) in passToUpdate:
                self.log(3, '   %s.%s %s:%s-%s' % (n, a, e, v, r))
                pkgstring = '%s:%s-%s-%s.%s' % (e,n,v,r,a)
                updatelist.append(pkgstring)
            self.updatePkgs(userlist=updatelist, quiet=1)

        if len(self.tsInfo) > oldcount:
            return 2, ['Package(s) to install']
        return 0, ['Nothing to do']
        
        
    def updatePkgs(self, userlist=None, quiet=0):
        """take user commands and populate transaction wrapper with 
           packages to be updated"""
        
        # if there is no userlist, then do global update below
        # this is probably 90% of the calls
        # if there is a userlist then it's for updating pkgs, not obsoleting
        
        oldcount = len(self.tsInfo)
        if not userlist:
            userlist = self.extcmds
        self.doRepoSetup()
        avail = self.pkgSack.simplePkgList()
        self.doRpmDBSetup()
        installed = self.rpmdb.getPkgList()
        self.doUpdateSetup()
        updates = self.up.getUpdatesTuples()
        if self.conf.getConfigOption('obsoletes'):
            obsoletes = self.up.getObsoletesTuples(newest=1)
        else:
            obsoletes = []

        if len(userlist) == 0: # simple case - do them all
            for (obsoleting, installed) in obsoletes:
                obsoleting_pkg = self.getPackageObject(obsoleting)
                installed_pkg =  YumInstalledPackage(self.rpmdb.returnHeaderByTuple(installed)[0])
                self.tsInfo.addObsoleting(obsoleting_pkg, installed_pkg)
                self.tsInfo.addObsoleted(installed_pkg, obsoleting_pkg)
                                
            for (new, old) in updates:
                txmbrs = self.tsInfo.getMembers(pkgtup=old)

                if txmbrs and txmbrs[0].output_state == 'obsoleted':
                    self.log(5, 'Not Updating Package that is already obsoleted: %s.%s %s:%s-%s' % old)
                else:
                    updating_pkg = self.getPackageObject(new)
                    updated_pkg = YumInstalledPackage(self.rpmdb.returnHeaderByTuple(old)[0])
                    self.tsInfo.addUpdate(updating_pkg, updated_pkg)


        else:
            # go through the userlist - look for items that are local rpms. If we find them
            # pass them off to localInstall() and then move on
            localupdates = []
            for item in userlist:
                if os.path.exists(item) and item[-4:] == '.rpm': # this is hurky, deal w/it
                    localupdates.append(item)
            
            if len(localupdates) > 0:
                val, msglist = self.localInstall(filelist=localupdates, updateonly=1)
                for item in localupdates:
                    userlist.remove(item)
                
            # we've got a userlist, match it against updates tuples and populate
            # the tsInfo with the matches
            updatesPo = []
            for (new, old) in updates:
                (n,a,e,v,r) = new
                updatesPo.extend(self.pkgSack.searchNevra(name=n, arch=a, epoch=e, 
                                 ver=v, rel=r))
                                 
            exactmatch, matched, unmatched = yum.packages.parsePackages(
                                                updatesPo, userlist, casematch=1)
            for userarg in unmatched:
                if not quiet:
                    self.errorlog(1, 'Could not find update match for %s' % userarg)

            updateMatches = yum.misc.unique(matched + exactmatch)
            for po in updateMatches:
                for (new, old) in updates:
                    if po.pkgtup == new:
                        updated_pkg = YumInstalledPackage(self.rpmdb.returnHeaderByTuple(old)[0])
                        self.tsInfo.addUpdate(po, updated_pkg)


        if len(self.tsInfo) > oldcount:
            change = len(self.tsInfo) - oldcount
            msg = '%d packages marked for Update/Obsoletion' % change
            return 2, [msg]
        else:
            return 0, ['No Packages marked for Update/Obsoletion']


        
    
    def erasePkgs(self, userlist=None):
        """take user commands and populate a transaction wrapper with packages
           to be erased/removed"""
        
        oldcount = len(self.tsInfo)
        
        if not userlist:
            userlist = self.extcmds
        
        self.doRpmDBSetup()
        installed = []
        for hdr in self.rpmdb.getHdrList():
            po = YumInstalledPackage(hdr)
            installed.append(po)
        
        if len(userlist) > 0: # if it ain't well, that'd be real _bad_ :)
            exactmatch, matched, unmatched = yum.packages.parsePackages(
                                             installed, userlist, casematch=1)
            erases = yum.misc.unique(matched + exactmatch)

        if unmatched:
            for arg in unmatched:
                try:
                    depmatches = self.returnInstalledPackagesByDep(arg)
                except yum.Errors.YumBaseError, e:
                    self.errorlog(0, _('%s') % e)
                    continue
                    
                if not depmatches:
                    self.errorlog(0, _('No Match for argument: %s') % arg)
                else:
                    erases.extend(depmatches)
            
        for pkg in erases:
            self.tsInfo.addErase(pkg)
        
        if len(self.tsInfo) > oldcount:
            change = len(self.tsInfo) - oldcount
            msg = '%d packages marked for removal' % change
            return 2, [msg]
        else:
            return 0, ['No Packages marked for removal']
    
    def localInstall(self, filelist=None, updateonly=0):
        """handles installs/updates of rpms provided on the filesystem in a 
           local dir (ie: not from a repo)"""
           
        # read in each package into a YumLocalPackage Object
        # append it to self.localPackages
        # check if it can be installed or updated based on nevra versus rpmdb
        # don't import the repos until we absolutely need them for depsolving
        
        oldcount = len(self.tsInfo)
        
        if not filelist:
            filelist = self.extcmds
        
        if len(filelist) == 0:
            return 0, ['No Packages Provided']
        
        self.doRpmDBSetup()
        installpkgs = []
        updatepkgs = []
        donothingpkgs = []
        
        for pkg in filelist:
            try:
                po = YumLocalPackage(ts=self.read_ts, filename=pkg)
            except yum.Errors.MiscError, e:
                self.errorlog(0, 'Cannot open file: %s. Skipping.' % pkg)
                continue
            self.log(2, 'Examining %s: %s' % (po.localpath, po))

            # everything installed that matches the name
            installedByKey = self.rpmdb.returnTupleByKeyword(name=po.name)
            # go through each package 
            if len(installedByKey) == 0: # nothing installed by that name
                if updateonly:
                    self.errorlog(2, 'Package %s not installed, cannot update it. Run yum install to install it instead.' % po.name)
                else:
                    installpkgs.append(po)
                continue

            for instTup in installedByKey:
                installed_pkg = YumInstalledPackage(self.rpmdb.returnHeaderByTuple(instTup)[0])
                (n, a, e, v, r) = po.pkgtup
                (n2, a2, e2, v2, r2) = installed_pkg.pkgtup
                rc = compareEVR((e2, v2, r2), (e, v, r))
                if rc < 0: # we're newer - this is an update, pass to them
                    if n2 in self.conf.exactarchlist:
                        if a == a2:
                            updatepkgs.append((po, installed_pkg))
                            continue
                        else:
                            donothingpkgs.append(po)
                            continue
                    else:
                        updatepkgs.append((po, installed_pkg))
                        continue
                elif rc == 0: # same, ignore
                    donothingpkgs.append(po)
                    continue
                elif rc > 0: 
                    donothingpkgs.append(po)
                    continue


        for po in installpkgs:
            self.log(2, 'Marking %s to be installed' % po.localpath)
            self.localPackages.append(po)
            self.tsInfo.addInstall(po)
        
        for (po, oldpo) in updatepkgs:
            self.log(2, 'Marking %s as an update to %s' % (po.localpath, oldpo))
            self.localPackages.append(po)
            self.tsInfo.addUpdate(po, oldpo)
        
        for po in donothingpkgs:
            self.log(2, '%s: does not update installed package.' % po.localpath)
        
        if len(self.tsInfo) > oldcount:
            
            return 2, ['Package(s) to install']
        return 0, ['Nothing to do']
        
            
        
        
    def returnPkgLists(self):
        """Returns packages lists based on arguments on the cli.returns a 
           GenericHolder instance with the following lists defined:
           available = list of packageObjects
           installed = list of packageObjects
           updates = tuples of packageObjects (updating, installed)
           extras = list of packageObjects
           obsoletes = tuples of packageObjects (obsoleting, installed)
           recent = list of packageObjects
           """
        
        special = ['available', 'installed', 'all', 'extras', 'updates', 'recent',
                   'obsoletes']
        
        pkgnarrow = 'all'
        if len(self.extcmds) > 0:
            if self.extcmds[0] in special:
                pkgnarrow = self.extcmds.pop(0)
            
        ypl = self.doPackageLists(pkgnarrow=pkgnarrow)
        
        # rework the list output code to know about:
        # obsoletes output
        # the updates format

        def _shrinklist(lst, args):
            if len(lst) > 0 and len(args) > 0:
                self.log(4, 'Matching packages for package list to user args')
                exactmatch, matched, unmatched = yum.packages.parsePackages(lst, args)
                return yum.misc.unique(matched + exactmatch)
            else:
                return lst
        
        ypl.updates = _shrinklist(ypl.updates, self.extcmds)
        ypl.installed = _shrinklist(ypl.installed, self.extcmds)
        ypl.available = _shrinklist(ypl.available, self.extcmds)
        ypl.recent = _shrinklist(ypl.recent, self.extcmds)
        ypl.extras = _shrinklist(ypl.extras, self.extcmds)
        ypl.obsoletes = _shrinklist(ypl.obsoletes, self.extcmds)
        
#        for lst in [ypl.obsoletes, ypl.updates]:
#            if len(lst) > 0 and len(self.extcmds) > 0:
#                self.log(4, 'Matching packages for tupled package list to user args')
#                for (pkg, instpkg) in lst:
#                    exactmatch, matched, unmatched = yum.packages.parsePackages(lst, self.extcmds)
                    
        return ypl

    def search(self, args=None):
        """cli wrapper method for module search function, searches simple
           text tags in a package object"""
        
        # call the yum module search function with lists of tags to search
        # and what to search for
        # display the list of matches
        if not args:
            args = self.extcmds
            
        searchlist = ['name', 'summary', 'description', 'packager', 'group', 'url']
        matching = self.searchPackages(searchlist, args, callback=self.matchcallback)

        if len(matching.keys()) == 0:
            return 0, ['No Matches found']
        return 0, []

    def deplist(self, args=None):
       """cli wrapper method for findDeps method takes a list of packages and 
       returns a formatted deplist for that package"""

       if not args:
          args = self.extcmds

       results = self.findDeps(args)
       self.depListOutput(results)

       return 0, []

    def provides(self, args=None):
        """use the provides methods in the rpmdb and pkgsack to produce a list 
           of items matching the provides strings. This is a cli wrapper to the 
           module"""
        if not args:
            args = self.extcmds
        
        matching = self.searchPackageProvides(args, callback=self.matchcallback)
        
        if len(matching.keys()) == 0:
            return 0, ['No Matches found']
        
        return 0, []
    
    def resolveDepCli(self, args=None):
        """returns a package (one per user arg) that provide the supplied arg"""
        
        if not args:
            args = self.extcmds
        
        for arg in args:
            try:
                pkg = self.returnPackageByDep(arg)
            except yum.Errors.YumBaseError, e:
                self.errorlog(0, _('No Package Found for %s') % arg)
            else:
                msg = '%s:%s-%s-%s.%s' % (pkg.epoch, pkg.name, pkg.version, pkg.release, pkg.arch)
                self.log(0, msg)

        return 0, []
    
    def cleanCli(self, userlist=None):
        if userlist is None:
            userlist = self.extcmds
        hdrcode = pkgcode = xmlcode = piklcode = dbcode = 0
        pkgresults = hdrresults = xmlresults = piklresults = dbresults = []

        if 'all' in self.extcmds:
            self.log(2, 'Cleaning up Everything')
            pkgcode, pkgresults = self.cleanPackages()
            hdrcode, hdrresults = self.cleanHeaders()
            xmlcode, xmlresults = self.cleanMetadata()
            dbcode, dbresults = self.cleanSqlite()
            piklcode, piklresults = self.cleanPickles()
            
            code = hdrcode + pkgcode + xmlcode + piklcode + dbcode
            results = hdrresults + pkgresults + xmlresults + piklresults + dbresults
            for msg in results:
                self.log(2, msg)
            return code, []
            
        if 'headers' in self.extcmds:
            self.log(2, 'Cleaning up Headers')
            hdrcode, hdrresults = self.cleanHeaders()
        if 'packages' in self.extcmds:
            self.log(2, 'Cleaning up Packages')
            pkgcode, pkgresults = self.cleanPackages()
        if 'metadata' in self.extcmds:
            self.log(2, 'Cleaning up xml metadata')
            xmlcode, xmlresults = self.cleanMetadata()
        if 'cache' in self.extcmds:
            self.log(2, 'Cleaning up pickled cache')
            piklcode, piklresults =  self.cleanPickles()
        if 'dbcache' in self.extcmds:
            self.log(2, 'Cleaning up database cache')
            dbcode, dbresults =  self.cleanSqlite()
            
        code = hdrcode + pkgcode + xmlcode + piklcode + dbcode
        results = hdrresults + pkgresults + xmlresults + piklresults + dbresults
        for msg in results:
            self.log(2, msg)
        return code, []

    def returnGroupLists(self, userlist=None):

        uservisible=1
        if userlist is None:
            userlist = self.extcmds
            
        if len(userlist) > 0:
            if userlist[0] == 'hidden':
                uservisible=0

        installed, available = self.doGroupLists(uservisible=uservisible)

        if len(installed) > 0:
            self.log(2, 'Installed Groups:')
            for group in installed:
                self.log(2, '   %s' % group)
        
        if len(available) > 0:
            self.log(2, 'Available Groups:')
            for group in available:
                self.log(2, '   %s' % group)

            
        return 0, ['Done']
    
    def returnGroupInfo(self, userlist=None):
        """returns complete information on a list of groups"""
        if userlist is None:
            userlist = self.extcmds
        
        for group in userlist:
            if self.groupInfo.groupExists(group):
                self.displayPkgsInGroups(group)
            else:
                self.errorlog(1, 'Warning: Group %s does not exist.' % group)
        
        return 0, []
        
    def installGroups(self, grouplist=None):
        """for each group requested attempt to install all pkgs/metapkgs of default
           or mandatory. Also recurse lists of groups to provide for them too."""
        
        if grouplist is None:
            grouplist = self.extcmds
        
        self.doRepoSetup()
        pkgs = [] # package objects to be installed
        installed = self.rpmdb.getPkgList()
        availablepackages = {}
        for po in self.pkgSack.returnPackages():
            if po.pkgtup not in installed:
                    availablepackages[po.name] = 1

        for group in grouplist:
            if not self.groupInfo.groupExists(group):
                self.errorlog(0, _('Warning: Group %s does not exist.') % group)
                continue
            pkglist = self.groupInfo.pkgTree(group)
            for pkg in pkglist:
                if availablepackages.has_key(pkg):
                    pkgs.append(pkg)
                    self.log(4, 'Adding package %s for groupinstall of %s.' % (pkg, group))

        if len(pkgs) > 0:
            self.log(2, 'Passing package list to Install Process')
            self.log(4, 'Packages being passed:')
            for pkg in pkgs:
                self.log(4, '%s' % pkg)
            return self.installPkgs(userlist=pkgs)
        else:
            return 0, ['No packages in any requested group available to install']

    
    def updateGroups(self, grouplist=None):
        """get list of any pkg in group that is installed, check to update it
           get list of any mandatory or default pkg attempt to update it if it is installed
           or install it if it is not installed"""

        if grouplist is None:
            grouplist = self.extcmds
        
        if len(grouplist) == 0:
            self.usage()
            
        self.doRepoSetup()
        self.doUpdateSetup()
        
        grouplist.sort()
        updatesbygroup = []
        installsbygroup = []
        updateablenames = []
        
        for group in grouplist:
            if not self.groupInfo.groupExists(group):
                self.errorlog(0, _('Warning: Group %s does not exist.') % group)
                continue

            required = self.groupInfo.requiredPkgs(group)
            all = self.groupInfo.pkgTree(group)
            for pkgn in all:
                if self.rpmdb.installed(name=pkgn):
                    if len(self.up.getUpdatesList(name=pkgn)) > 0:
                        updatesbygroup.append((group, pkgn))
                else:
                    if pkgn in required:
                        installsbygroup.append((group, pkgn))
        
        updatepkgs = []
        installpkgs = []
        for (group, pkg) in updatesbygroup:
            self.log(2, _('From %s updating %s') % (group, pkg))
            updatepkgs.append(pkg)
        for (group, pkg) in installsbygroup:
            self.log(2, _('From %s installing %s') % (group, pkg))
            installpkgs.append(pkg)

        

        if len(installpkgs) > 0:
            self.installPkgs(userlist=installpkgs)
        
        if len(updatepkgs) > 0:
            self.updatePkgs(userlist=updatepkgs, quiet=1)
        
        if len(self.tsInfo) > 0:
            return 2, ['Group updating']
        else:
            return 0, [_('Nothing in any group to update or install')]
    
    def removeGroups(self, grouplist=None):
        """Remove only packages of the named group(s). Do not recurse."""

        if grouplist is None:
            grouplist = self.extcmds
        
        if len(grouplist) == 0:
            self.usage()
        
        erasesbygroup = []
        for group in grouplist:
            if not self.groupInfo.groupExists(group):
                self.errorlog(0, _('Warning: Group %s does not exist.') % group)
                continue
        
            allpkgs = self.groupInfo.allPkgs(group)
            for pkg in allpkgs:
                if self.rpmdb.installed(name=pkg):
                    erasesbygroup.append((group, pkg))

        erases = []
        for (group, pkg) in erasesbygroup:
            self.log(2, _('From %s removing %s') % (group, pkg))
            erases.append(pkg)
        
        if len(erases) > 0:
            return self.erasePkgs(userlist=erases)
        else:
            return 0, ['No packages to remove from groups']


    def _promptWanted(self):
        # shortcut for the always-off/always-on options
        if self.conf.getConfigOption('assumeyes'):
            return False
        if self.conf.getConfigOption('alwaysprompt'):
            return True
        
        # prompt if:
        #  package was added to fill a dependency
        #  package is being removed
        #  package wasn't explictly given on the command line
        for txmbr in self.tsInfo.getMembers():
            if txmbr.isDep or \
                   txmbr.ts_state == 'e' or \
                   txmbr.name not in self.extcmds:
                return True
        
        # otherwise, don't prompt        
        return False

    def usage(self):
        '''Print out command line usage
        '''
        print
        self.optparser.print_help()

class YumOptionParser(OptionParser):
    '''Subclass that makes some minor tweaks to make OptionParser do things the
    "yum way".
    '''

    def __init__(self, base, **kwargs):
        OptionParser.__init__(self, **kwargs)
        self.base = base

    def error(self, msg):
        '''This method is overridden so that error output goes to errorlog
        '''
        self.print_usage()
        self.base.errorlog(0, "Command line error: "+msg)
        sys.exit(1)

def _filtercmdline(novalopts, valopts, args):
    '''Keep only specific options from the command line argument list

    This function allows us to peek at specific command line options when using
    the optparse module. This is useful when some options affect what other
    options should be available.

    @param novalopts: A sequence of options to keep that don't take an argument.
    @param valopts: A sequence of options to keep that take a single argument.
    @param args: The command line arguments to parse (as per sys.argv[:1]
    @return: A list of strings containing the filtered version of args.

    Will raise ValueError if there was a problem parsing the command line.
    '''
    out = []
    args = list(args)       # Make a copy because this func is destructive

    while len(args) > 0:
        a = args.pop(0)
        if '=' in a:
            opt, _ = a.split('=', 1)
            if opt in valopts:
                out.append(a)

        elif a in novalopts:
            out.append(a)

        elif a in valopts:
            if len(args) < 1:
                raise ValueError
            next = args.pop(0)
            if next.startswith('-'):
                raise ValueError

            out.extend([a, next])
       
        else:
            # Check for single letter options that take a value, where the
            # value is right up against the option
            for opt in valopts:
                if len(opt) == 2 and a.startswith(opt):
                    out.append(a)

    return out