File: yum-config-manager.py

package info (click to toggle)
yum-utils 1.1.31-2~bpo7%2B1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy-backports
  • size: 1,776 kB
  • sloc: python: 10,088; sh: 416; makefile: 217; perl: 206; xml: 4
file content (234 lines) | stat: -rwxr-xr-x 8,002 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/python -tt

import os, os.path
import sys
import re
import yum
sys.path.insert(0,'/usr/share/yum-cli')
from utils import YumUtilBase
import logging

from iniparse import INIConfig

from yum.parser import varReplace

# Regular expressions to sanitise cache filenames
re_url_scheme    = re.compile(r'^\w+:/*(\w+:|www\.)?')
re_slash         = re.compile(r'[?/:&#|]+')
re_initial_cruft = re.compile(r'^[,.]*')
re_final_cruft   = re.compile(r'[,.]*$')

def sanitize_url_to_fs(url):
    """Return a filename suitable for the filesystem

    Strips dangerous and common characters to create a filename we
    can use to store the cache in.
    """
    
    # code taken and modified from planet venus code base:
    # http://intertwingly.net/code/venus/LICENCE

    try:
        if re_url_scheme.match(url):
            if isinstance(url,str):
                url=url.decode('utf-8').encode('idna')
            else:
                url=url.encode('idna')
    except:
        pass
    if isinstance(url,unicode):
        url=url.encode('utf-8')
    url = re_url_scheme.sub("", url)
    url = re_slash.sub("_", url)
    url = re_initial_cruft.sub("", url)
    url = re_final_cruft.sub("", url)

    # limit length of url
    if len(url)>250:
        parts=url.split(',')
        for i in range(len(parts),0,-1):
            if len(','.join(parts[:i])) < 220:
                url = ','.join(parts[:i]) + ',' + \
                    yum.misc.checksum('md5', (','.join(parts[i:])))
                break

    return url



def writeRawConfigFile(filename, section_id, yumvar,
                       cfgoptions, items, optionobj,
                       only=None):
    """
    From writeRawRepoFile, but so we can alter [main] too.
    """
    ini = INIConfig(open(filename))

    osection_id = section_id
    # b/c repoids can have $values in them we need to map both ways to figure
    # out which one is which
    if section_id not in ini._sections:
        for sect in ini._sections.keys():
            if varReplace(sect, yumvar) == section_id:
                section_id = sect

    # Updated the ConfigParser with the changed values
    cfgOptions = cfgoptions(osection_id)
    for name,value in items():
        if value is None: # Proxy
            continue

        if only is not None and name not in only:
            continue

        option = optionobj(name)
        ovalue = option.tostring(value)
        #  If the value is the same, but just interpreted ... when we don't want
        # to keep the interpreted values.
        if (name in ini[section_id] and
            ovalue == varReplace(ini[section_id][name], yumvar)):
            ovalue = ini[section_id][name]

        if name not in cfgOptions and option.default == value:
            continue

        ini[section_id][name] = ovalue
    fp =file(filename, "w")
    fp.write(str(ini))
    fp.close()

NAME = 'yum-config-manager'
VERSION = '1.0'
USAGE = '"yum-config-manager [options] [section]'

yum.misc.setup_locale()

yb = YumUtilBase(NAME, VERSION, USAGE)
logger = logging.getLogger("yum.verbose.cli.yum-config-manager")
yb.preconf.debuglevel = 0
yb.preconf.errorlevel = 0
yb.optparser = yb.getOptionParser()
if hasattr(yb, 'getOptionGroup'): # check if the group option API is available
    group = yb.getOptionGroup()
else:
    group = yb.optparser
group.add_option("--save", default=False, action="store_true",
          help='save the current options (useful with --setopt)')
group.add_option("--enable", default=False, action="store_true",
          help='enable the specified repos (automatically saves)')
group.add_option("--disable", default=False, action="store_true",
          help='disable the specified repos (automatically saves)')
group.add_option("--add-repo", default=[], dest='addrepo', action='append',
          help='add (and enable) the repo from the specified file or url')
try:
    opts = yb.doUtilConfigSetup()
except yum.Errors.RepoError, e:
    logger.error(str(e))
    sys.exit(50)

if opts.save or opts.enable or opts.disable or opts.addrepo:
    if yb.conf.uid != 0:
        logger.error("You must be root to change the yum configuration.")
        sys.exit(50)
        
args = set(yb.cmds)

if opts.enable and opts.disable:
    logger.error("Error: Trying to enable and disable repos.")
    opts.enable = opts.disable = False
if opts.enable and not args:
    logger.error("Error: Trying to enable already enabled repos.")
    opts.enable = False

only = None

if (not args and not opts.addrepo) or 'main' in args:
    print yb.fmtSection('main')
    print yb.conf.dump()
    if opts.save and hasattr(yb, 'main_setopts') and yb.main_setopts:
        fn = '/etc/yum/yum.conf'
        if not os.path.exists(fn):
            # Try the old default
            fn = '/etc/yum.conf'
        ybc = yb.conf
        writeRawConfigFile(fn, 'main', ybc.yumvar,
                           ybc.cfg.options, ybc.iteritems, ybc.optionobj,
                           only)

if opts.enable or opts.disable:
    opts.save = True
    if not hasattr(yb, 'repo_setopts') or not yb.repo_setopts:
        only = ['enabled']

if args:
    repos = yb.repos.findRepos(','.join(args))
else:
    repos = yb.repos.listEnabled()

if not opts.addrepo:
    for repo in sorted(repos):
        print yb.fmtSection('repo: ' + repo.id)
        if opts.enable and not repo.enabled:
            repo.enable()
        elif opts.disable and repo.enabled:
            repo.disable()
        print repo.dump()
        if (opts.save and
            (only or (hasattr(yb, 'repo_setopts') and repo.id in yb.repo_setopts))):
            writeRawConfigFile(repo.repofile, repo.id, repo.yumvar,
                               repo.cfg.options, repo.iteritems, repo.optionobj,
                               only)

if opts.addrepo:
    # figure out the best reposdir by seeing which dirs exist
    myrepodir = None
    for rdir in yb.conf.reposdir:
        if os.path.exists(rdir): # take the first one that exists
            myrepodir = rdir
            break
    
    if not myrepodir:
        myrepodir = yb.conf.reposdir[0]
        os.makedirs(myrepodir)
        
    for url in opts.addrepo:
        print 'adding repo from: %s' % url
        if url.endswith('.repo'): # this is a .repo file - fetch it, put it in our reposdir and enable it
            destname = os.path.basename(url)
            destname = myrepodir + '/' + destname
            # this sucks - but take the first repo we come to that's enabled
            # and steal it's grabber object - it could be proxy-laden but that's the risk we take
            # grumbledy grumble
            grabber = yb.repos.listEnabled()[0].grabfunc            
            print 'grabbing file %s to %s' % (url, destname)
            try:
                result  = grabber.urlgrab(url, filename=destname, copy_local=True)
            except (IOError, OSError, yum.Errors.YumBaseError), e:
                logger.error('Could not fetch/save url %s to file %s: %s'  % (url, destname, e))
                continue
            else:
                print 'repo saved to %s' % result
            
        else:
            repoid = sanitize_url_to_fs(url)
            reponame = 'added from: %s' % url
            repofile = myrepodir + '/' + repoid + '.repo'
            try:
                thisrepo = yb.add_enable_repo(repoid, baseurl=[url], name=reponame)
            except yum.Errors.DuplicateRepoError, e:
                logger.error('Cannot add repo from %s as is a duplicate of an existing repo' % url)
                continue
            repoout = """\n[%s]\nname=%s\nbaseurl=%s\nenabled=1\n\n""" % (repoid, reponame, url)

            try:
                fo = open(repofile, 'w+')
                fo.write(repoout)
                print repoout
            except (IOError, OSError), e:
                logger.error('Could not save repo to repofile %s: %s' % (repofile, e))
                continue
            else:
                fo.close()