def inifile_readstring(inifilename,section,key,default=None): """Read a string parameter from inifile""" inifile = RawConfigParser() inifile.read(inifilename) if inifile.has_section(section) and inifile.has_option(section,key): return inifile.get(section,key) else: return default
def inifile_readstring(inifilename, section, key, default=None): """Read a string parameter from inifile""" inifile = RawConfigParser() inifile.read(inifilename) if inifile.has_section(section) and inifile.has_option(section, key): return inifile.get(section, key) else: return default
def inifile_readstring(inifilename, section, key, default=None): """Read a string parameter from inifile >>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.2') >>> print inifile_readstring('c:/tranquilit/wapt/tests/test.ini','global','version') 1.1.2 >>> print inifile_readstring('c:/tranquilit/wapt/tests/test.ini','global','undefaut','defvalue') defvalue """ inifile = RawConfigParser() inifile.read(inifilename) if inifile.has_section(section) and inifile.has_option(section, key): return inifile.get(section, key) else: return default
def inifile_hasoption(inifilename, section, key): """Check if an option is present in section of the inifile Args: inifilename (str): Path to the ini file section (str): section key (str): value key to check Returns: boolean : True if the key exists >>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.2') >>> print inifile_hasoption('c:/tranquilit/wapt/tests/test.ini','global','version') True >>> print inifile_hasoption('c:/tranquilit/wapt/tests/test.ini','global','dontexist') False """ inifile = RawConfigParser() inifile.read(inifilename) return inifile.has_section(section) and inifile.has_option(section, key)
def inifile_deleteoption(inifilename, section, key): """Remove a key within the section of the inifile Args: inifilename (str): Path to the ini file section (str): section key (str): value key of option to remove Returns: boolean : True if the key/option has been removed >>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.2') >>> print inifile_hasoption('c:/tranquilit/wapt/tests/test.ini','global','version') True >>> print inifile_deleteoption('c:/tranquilit/wapt/tests/test.ini','global','version') False """ inifile = RawConfigParser() inifile.read(inifilename) inifile.remove_option(section, key) inifile.write(open(inifilename, 'w')) return inifile.has_section(section) and not inifile.has_option( section, key)
def enable_yum_plugins(cls): """ This function tries to enable yum plugins: subscription-manager and product-id. It takes no action, when automatic enabling of yum plugins is disabled in rhsm.conf. :return: It returns list of enabled plugins """ # When user doesn't want to automatically enable yum plugins, then return empty list if cls.is_auto_enable_enabled() is False: log.info( 'The rhsm.auto_enable_yum_plugins is disabled. Skipping the enablement of yum plugins.' ) return [] log.debug('The rhsm.auto_enable_yum_plugins is enabled') # List of successfully enabled plugins enabled_yum_plugins = [] plugin_dir = "" if version.use_dnf: plugin_dir = cls.DNF_PLUGIN_DIR else: plugin_dir = cls.YUM_PLUGIN_DIR # Go through the list of yum plugins and try to find configuration # file of these plugins. for yum_plugin_name in cls.YUM_PLUGINS: yum_plugin_file_name = plugin_dir + '/' + yum_plugin_name + '.conf' yum_plugin_config = ConfigParser() try: result = yum_plugin_config.read(yum_plugin_file_name) except Exception as err: # Capture all errors during reading yum plugin conf file # report them and skip this conf file log.error( "Error during reading yum plugin config file '%s': %s. Skipping this file." % (yum_plugin_file_name, err)) continue if len(result) == 0: log.info( 'Configuration file of yum plugin: "%s" cannot be read' % yum_plugin_file_name) continue is_plugin_enabled = False if not yum_plugin_config.has_section('main'): log.warn( 'Configuration file of yum plugin: "%s" does not include main section. Adding main section.' % yum_plugin_file_name) yum_plugin_config.add_section('main') elif yum_plugin_config.has_option('main', 'enabled'): try: # Options 'enabled' can be 0 or 1 is_plugin_enabled = yum_plugin_config.getint( 'main', 'enabled') except ValueError: try: # Options 'enabled' can be also: true or false is_plugin_enabled = yum_plugin_config.getboolean( 'main', 'enabled') except ValueError: log.warn( "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)" % yum_plugin_file_name) if is_plugin_enabled == cls.YUM_PLUGIN_ENABLED: log.debug('Yum plugin: "%s" already enabled. Nothing to do.' % yum_plugin_file_name) else: log.warn('Enabling yum plugin: "%s".' % yum_plugin_file_name) # Change content of plugin configuration file and enable this plugin. with open(yum_plugin_file_name, 'w') as cfg_file: yum_plugin_config.set('main', 'enabled', cls.YUM_PLUGIN_ENABLED) yum_plugin_config.write(cfg_file) enabled_yum_plugins.append(yum_plugin_file_name) return enabled_yum_plugins
def _enable_plugins(cls, pkg_mgr_name, plugin_dir): """ This class method tries to enable plugins for DNF or YUM :param pkg_mgr_name: It can be "dnf" or "yum" :type pkg_mgr_name: str :param plugin_dir: Directory with configuration files for (dnf/yum) plugins :type plugin_dir: str :return: """ # List of successfully enabled plugins enabled_lugins = [] # Go through the list of yum plugins and try to find configuration # file of these plugins. for plugin_name in cls.PLUGINS: plugin_file_name = plugin_dir + '/' + plugin_name + '.conf' plugin_config = ConfigParser() try: result = plugin_config.read(plugin_file_name) except Exception as err: # Capture all errors during reading yum plugin conf file # report them and skip this conf file log.error( "Error during reading %s plugin config file '%s': %s. Skipping this file." % (pkg_mgr_name, plugin_file_name, err)) continue if len(result) == 0: log.info( 'Configuration file of %s plugin: "%s" cannot be read' % (pkg_mgr_name, plugin_file_name)) continue is_plugin_enabled = False if not plugin_config.has_section('main'): log.warning( 'Configuration file of %s plugin: "%s" does not include main section. Adding main section.' % (pkg_mgr_name, plugin_file_name)) plugin_config.add_section('main') elif plugin_config.has_option('main', 'enabled'): try: # Options 'enabled' can be 0 or 1 is_plugin_enabled = plugin_config.getint('main', 'enabled') except ValueError: try: # Options 'enabled' can be also: true or false is_plugin_enabled = plugin_config.getboolean( 'main', 'enabled') except ValueError: log.warning( "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)" % plugin_file_name) if is_plugin_enabled == cls.PLUGIN_ENABLED: log.debug('%s plugin: "%s" already enabled. Nothing to do.' % (pkg_mgr_name, plugin_file_name)) else: log.warning('Enabling %s plugin: "%s".' % (pkg_mgr_name, plugin_file_name)) # Change content of plugin configuration file and enable this plugin. with open(plugin_file_name, 'w') as cfg_file: plugin_config.set('main', 'enabled', cls.PLUGIN_ENABLED) plugin_config.write(cfg_file) enabled_lugins.append(plugin_file_name) return enabled_lugins
def _enable_plugins(cls, pkg_mgr_name, plugin_dir): """ This class method tries to enable plugins for DNF or YUM :param pkg_mgr_name: It can be "dnf" or "yum" :type pkg_mgr_name: str :param plugin_dir: Directory with configuration files for (dnf/yum) plugins :type plugin_dir: str :return: """ # List of successfully enabled plugins enabled_lugins = [] # Go through the list of yum plugins and try to find configuration # file of these plugins. for plugin_name in cls.PLUGINS: plugin_file_name = plugin_dir + '/' + plugin_name + '.conf' plugin_config = ConfigParser() try: result = plugin_config.read(plugin_file_name) except Exception as err: # Capture all errors during reading yum plugin conf file # report them and skip this conf file log.error( "Error during reading %s plugin config file '%s': %s. Skipping this file." % (pkg_mgr_name, plugin_file_name, err) ) continue if len(result) == 0: log.warn('Configuration file of %s plugin: "%s" cannot be read' % (pkg_mgr_name, plugin_file_name)) continue is_plugin_enabled = False if not plugin_config.has_section('main'): log.warning( 'Configuration file of %s plugin: "%s" does not include main section. Adding main section.' % (pkg_mgr_name, plugin_file_name) ) plugin_config.add_section('main') elif plugin_config.has_option('main', 'enabled'): try: # Options 'enabled' can be 0 or 1 is_plugin_enabled = plugin_config.getint('main', 'enabled') except ValueError: try: # Options 'enabled' can be also: true or false is_plugin_enabled = plugin_config.getboolean('main', 'enabled') except ValueError: log.warning( "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)" % plugin_file_name ) if is_plugin_enabled == cls.PLUGIN_ENABLED: log.debug('%s plugin: "%s" already enabled. Nothing to do.' % (pkg_mgr_name, plugin_file_name)) else: log.warning('Enabling %s plugin: "%s".' % (pkg_mgr_name, plugin_file_name)) # Change content of plugin configuration file and enable this plugin. with open(plugin_file_name, 'w') as cfg_file: plugin_config.set('main', 'enabled', cls.PLUGIN_ENABLED) plugin_config.write(cfg_file) enabled_lugins.append(plugin_file_name) return enabled_lugins
def main(): if len(args) == 0: print "ERROR : You must provide one action to perform" parser.print_usage() sys.exit(2) action = args[0] # Config file if not os.path.isfile(config_file): logger.error("Error : could not find file : " + config_file + ", please check the path") logger.debug("Config file: %s" % config_file) defaults = { "repositories": "", "repo_url": "", "default_source_url": "", "private_key": "", "public_cert": "", "default_development_base": "c:\tranquilit", "default_package_prefix": "tis", "default_sources_suffix": "wapt", "default_sources_url": "", "upload_cmd": "", "wapt_server": "", "loglevel": "info", } cp = RawConfigParser(defaults=defaults) cp.add_section("global") cp.read(config_file) global loglevel if not loglevel and cp.has_option("global", "loglevel"): loglevel = cp.get("global", "loglevel") setloglevel(loglevel) mywapt = Wapt(config=cp) if options.wapt_url: mywapt.wapt_repourl = options.wapt_url if options.private_key: mywapt.private_key = options.private_key else: mywapt.private_key = cp.get("global", "private_key") mywapt.dry_run = options.dry_run # logger.info("Main wapt Repository %s" % mywapt.wapt_repourl) logger.debug("WAPT base directory : %s" % mywapt.wapt_base_dir) logger.debug("Package cache dir : %s" % mywapt.packagecachedir) logger.debug("WAPT DB Structure version;: %s" % mywapt.waptdb.db_version) try: params_dict = {} try: params_dict = json.loads(options.params.replace("'", '"')) except: raise Exception("Install Parameters must be in json format") if action == "install" or action == "download": if len(args) < 2: print "You must provide at least one package name" sys.exit(1) if os.path.isdir(args[1]) or os.path.isfile(args[1]): print "installing WAPT file %s" % args[1] if action == "install": mywapt.install_wapt(args[1], params_dict=params_dict) else: print "%sing WAPT packages %s" % (action, ",".join(args[1:])) if options.update_packages: print "Update package list" mywapt.update() result = mywapt.install( args[1:], force=options.force, params_dict=params_dict, download_only=(action == "download") ) print "\nResults :" if action <> "download": for k in ("install", "additional", "upgrade", "skipped", "errors"): if result.get(k, []): print "\n=== %s packages ===\n%s" % ( k, "\n".join( [" %-30s | %s (%s)" % (s[0], s[1].package, s[1].version) for s in result[k]] ), ) else: for k in ("downloaded", "skipped", "errors"): if result.get("downloads", {"downloaded": [], "skipped": [], "errors": []})[k]: print "\n=== %s packages ===\n%s" % ( k, "\n".join([" %s" % (s,) for s in result["downloads"][k]]), ) elif action == "download": if len(args) < 2: print "You must provide at least one package name to download" sys.exit(1) if options.update_packages: print "Update package list" mywapt.update() print "Downloading packages %s" % (",".join(args[1:]),) result = mywapt.download_packages(args[1:], usecache=not options.force) if result["downloaded"]: print "\nDownloaded packages : \n%s" % "\n".join([" %s" % p for p in result["downloaded"]]) if result["skipped"]: print "Skipped packages : \n%s" % "\n".join([" %s" % p for p in result["skipped"]]) if result["errors"]: logger.critical("Unable to download some files : %s" % (result["errors"],)) sys.exit(1) elif action == "show": if len(args) < 2: print "You must provide at least one package name to show" sys.exit(1) if os.path.isdir(args[1]) or os.path.isfile(args[1]): entry = PackageEntry().load_control_from_wapt(args[1]) print "%s" % entry else: print "Display package control data for %s\n" % (",".join(args[1:]),) if options.update_packages: print "Update package list" mywapt.update() for packagename in args[1:]: entries = mywapt.waptdb.packages_matching(packagename) if entries: for e in entries: print "%s\n" % e.ascontrol(with_non_control_attributes=True) else: print "None packages found matching package name and version" elif action == "show-params": if len(args) < 2: print "You must provide at one package name to show params for" sys.exit(1) for packagename in args[1:]: params = mywapt.waptdb.params(packagename) print "%s" % params elif action == "list-registry": print "%-39s%-70s%-20s%-70s" % ("UninstallKey", "Software", "Version", "Uninstallstring") print "-" * 39 + "-" * 70 + "-" * 20 + "-" * 70 for p in setuphelpers.installed_softwares(" ".join(args[1:])): print u"%-39s%-70s%-20s%-70s" % (p["key"], p["name"], p["version"], p["uninstall_string"]) elif action == "showlog": if len(args) < 2: print "You must provide at least one package name" sys.exit(1) for packagename in args[1:]: result = mywapt.last_install_log(packagename) print "Package : %s\nStatus : %s\n\nInstallation log:\n%s" % ( packagename, result["status"], result["log"], ) elif action == "remove": if len(args) < 2: print "You must provide at least one package name to remove" sys.exit(1) for packagename in args[1:]: print "Removing %s ..." % (packagename,), mywapt.remove(packagename, force=options.force) print "done" elif action == "session-setup": if len(args) < 2: print "You must provide at least one package to be configured in user's session" sys.exit(1) for packagename in args[1:]: print "Configuring %s ..." % (packagename,), mywapt.session_setup(packagename, params_dict=params_dict) print "done" elif action == "uninstall": # launch the setup.uninstall() procedure for the given packages # can be used when registering in registry a custom install with a python script if len(args) < 2: print "You must provide at least one package to be uninstalled" sys.exit(1) for packagename in args[1:]: print "uninstalling %s ..." % (packagename,), mywapt.uninstall(packagename, params_dict=params_dict) print "uninstall done" elif action == "update": print "Update package list" result = mywapt.update() print "Total packages : %i" % result["count"] print "Added packages : \n%s" % "\n".join([" %s (%s)" % p for p in result["added"]]) print "Removed packages : \n%s" % "\n".join([" %s (%s)" % p for p in result["removed"]]) print "Repositories URL : \n%s" % "\n".join([" %s" % p for p in result["repos"]]) elif action == "upgradedb": (old, new) = mywapt.waptdb.upgradedb() if old == new: print "No database upgrade required, current %s, required %s" % (old, mywapt.waptdb.curr_db_version) else: print "Old version : %s to new : %s" % (old, new) elif action == "upgrade": if options.update_packages: print "Update package list" mywapt.update() result = mywapt.upgrade() if not result["install"] and not result["additional"] and not result["upgrade"] and not result["skipped"]: print "Nothing to upgrade" else: for k in ("install", "additional", "upgrade", "skipped", "errors"): if result[k]: print "\n=== %s packages ===\n%s" % ( k, "\n".join([" %-30s | %s (%s)" % (s[0], s[1].package, s[1].version) for s in result[k]]), ) sys.exit(0) elif action == "list-upgrade": if options.update_packages: print "Update package list" mywapt.update() q = mywapt.list_upgrade() if not q: print "Nothing to upgrade" else: print ppdicttable([p[0] for p in q], [("package", 20), ("version", 10)]) elif action == "download-upgrade": if options.update_packages: print "Update package list" mywapt.update() result = mywapt.download_upgrades() print "Downloaded packages : \n%s" % "\n".join([" %s" % p for p in result["downloaded"]]) print "Skipped packages : \n%s" % "\n".join([" %s" % p for p in result["skipped"]]) if result["errors"]: logger.critical("Unable to download some files : %s" % (result["errors"],)) sys.exit(1) elif action == "update-packages": if len(args) < 2: print "You must provide the directory" sys.exit(1) print update_packages(args[1]) elif action == "sources": if len(args) < 2: print "You must provide the package name" sys.exit(1) os.startfile(mywapt.get_sources(args[1])) elif action == "make-template": if len(args) < 2: print "You must provide the installer path" sys.exit(1) source_dir = mywapt.maketemplate(*args[1:]) print "Template created. You can build the WAPT package by launching\n %s build-package %s" % ( sys.argv[0], source_dir, ) os.startfile(source_dir) elif action == "make-host-template": source_dir = mywapt.makehosttemplate(*args[1:]) print "Template created. You can build the WAPT package by launching\n %s build-package %s" % ( sys.argv[0], source_dir, ) os.startfile(source_dir) elif action == "build-package": if len(args) < 2: print "You must provide at least one source directory for package build" sys.exit(1) for source_dir in [os.path.abspath(p) for p in args[1:]]: if os.path.isdir(source_dir): print ("Building %s" % source_dir) result = mywapt.buildpackage( source_dir, inc_package_release=options.increlease, excludes=options.excludes.split(",") ) package_fn = result["filename"] if package_fn: print "Package content:" for f in result["files"]: print " %s" % f[0] print ("...done. Package filename %s" % (package_fn,)) def pwd_callback(*args): """Default password callback for opening private keys""" return open(options.private_key_passwd, "r").read() if mywapt.private_key: print ("Signing %s" % package_fn) if options.private_key_passwd: signature = mywapt.signpackage( package_fn, excludes=options.excludes.split(","), callback=pwd_callback ) else: signature = mywapt.signpackage(package_fn, excludes=options.excludes.split(",")) print "Package %s signed : signature :\n%s" % (package_fn, signature) else: logger.warning("No private key provided, package %s is unsigned !" % package_fn) if mywapt.upload_cmd: print "\nYou can upload to repository with\n %s upload-package %s " % ( sys.argv[0], package_fn, ) return 0 else: logger.critical("package not created") return 1 else: logger.critical("Directory %s not found" % source_dir) elif action == "sign-package": if len(args) < 2: print "You must provide at least one source directory or package to sign" sys.exit(1) for waptfile in [os.path.abspath(p) for p in args[1:]]: if os.path.isdir(waptfile) or os.path.isfile(waptfile): print ("Signing %s" % waptfile) signature = mywapt.signpackage(waptfile, excludes=options.excludes.split(",")) print "Package %s signed : signature :\n%s" % (waptfile, signature) else: logger.critical("Package %s not found" % waptfile) return 1 elif action == "upload-package": if len(args) < 2: print "You must provide a package to upload" sys.exit(1) waptfiles = [] for a in args[1:]: waptfiles += glob.glob(a) waptfile_arg = " ".join(['"%s"' % f for f in waptfiles]) print setuphelpers.run(mywapt.upload_cmd % {"waptfile": waptfile_arg}) if mywapt.after_upload: print setuphelpers.run(mywapt.after_upload % {"waptfile": waptfile_arg}) elif action == "search": if options.update_packages: print "Update package list" mywapt.update() result = mywapt.waptdb.packages_search(args[1:]) print ppdicttable(result, (("package", 30), ("version", 10), ("description", 80))) elif action == "cleanup": result = mywapt.cleanup() print "Removed files : \n%s" % "\n".join([" %s" % p for p in result]) elif action == "inventory": print mywapt.inventory() elif action == "setup-tasks": print mywapt.setup_tasks() elif action == "list": def cb(fieldname, value): if value and fieldname == "install_date": return value[0:16] else: return value print ppdicttable( mywapt.waptdb.installed_search(args[1:]).values(), (("package", 20), ("version", 15), ("install_status", 10), ("install_date", 16), ("description", 80)), callback=cb, ) else: print "Unknown action %s" % action sys.exit(1) except Exception, e: print "FATAL ERROR : %s" % e if logger.level == logging.DEBUG: raise sys.exit(3)
def enable_yum_plugins(cls): """ This function tries to enable yum plugins: subscription-manager and product-id. It takes no action, when automatic enabling of yum plugins is disabled in rhsm.conf. :return: It returns list of enabled plugins """ # When user doesn't want to automatically enable yum plugins, then return empty list if cls.is_auto_enable_enabled() is False: log.info('The rhsm.auto_enable_yum_plugins is disabled. Skipping the enablement of yum plugins.') return [] log.debug('The rhsm.auto_enable_yum_plugins is enabled') # List of successfully enabled plugins enabled_yum_plugins = [] # Go through the list of yum plugins and try to find configuration # file of these plugins. for yum_plugin_name in cls.YUM_PLUGINS: yum_plugin_file_name = cls.YUM_PLUGIN_DIR + '/' + yum_plugin_name + '.conf' yum_plugin_config = ConfigParser() try: result = yum_plugin_config.read(yum_plugin_file_name) except Exception as err: # Capture all errors during reading yum plugin conf file # report them and skip this conf file log.error( "Error during reading yum plugin config file '%s': %s. Skipping this file." % (yum_plugin_file_name, err) ) continue if len(result) == 0: log.info('Configuration file of yum plugin: "%s" cannot be read' % yum_plugin_file_name) continue is_plugin_enabled = False if not yum_plugin_config.has_section('main'): log.warn( 'Configuration file of yum plugin: "%s" does not include main section. Adding main section.' % yum_plugin_file_name ) yum_plugin_config.add_section('main') elif yum_plugin_config.has_option('main', 'enabled'): try: # Options 'enabled' can be 0 or 1 is_plugin_enabled = yum_plugin_config.getint('main', 'enabled') except ValueError: try: # Options 'enabled' can be also: true or false is_plugin_enabled = yum_plugin_config.getboolean('main', 'enabled') except ValueError: log.warn( "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)" % yum_plugin_file_name ) if is_plugin_enabled == cls.YUM_PLUGIN_ENABLED: log.debug('Yum plugin: "%s" already enabled. Nothing to do.' % yum_plugin_file_name) else: log.warn('Enabling yum plugin: "%s".' % yum_plugin_file_name) # Change content of plugin configuration file and enable this plugin. with open(yum_plugin_file_name, 'w') as cfg_file: yum_plugin_config.set('main', 'enabled', cls.YUM_PLUGIN_ENABLED) yum_plugin_config.write(cfg_file) enabled_yum_plugins.append(yum_plugin_file_name) return enabled_yum_plugins
def inifile_hasoption(inifilename,section,key): """Read a string parameter from inifile""" inifile = RawConfigParser() inifile.read(inifilename) return inifile.has_section(section) and inifile.has_option(section,key)
def inifile_hasoption(inifilename, section, key): """Read a string parameter from inifile""" inifile = RawConfigParser() inifile.read(inifilename) return inifile.has_section(section) and inifile.has_option(section, key)
def main(): if len(args) == 0: print "ERROR : You must provide one action to perform" parser.print_usage() sys.exit(2) action = args[0] # Config file if not os.path.isfile(config_file): logger.error("Error : could not find file : " + config_file + ", please check the path") logger.debug('Config file: %s' % config_file) defaults = { 'repositories': '', 'repo_url': '', 'default_source_url': '', 'private_key': '', 'public_cert': '', 'default_development_base': 'c:\tranquilit', 'default_package_prefix': 'tis', 'default_sources_suffix': 'wapt', 'default_sources_url': '', 'upload_cmd': '', 'wapt_server': '', 'loglevel': 'info', } cp = RawConfigParser(defaults=defaults) cp.add_section('global') cp.read(config_file) global loglevel if not loglevel and cp.has_option('global', 'loglevel'): loglevel = cp.get('global', 'loglevel') setloglevel(loglevel) mywapt = Wapt(config=cp) if options.wapt_url: mywapt.wapt_repourl = options.wapt_url if options.private_key: mywapt.private_key = options.private_key else: mywapt.private_key = cp.get('global', 'private_key') mywapt.dry_run = options.dry_run #logger.info("Main wapt Repository %s" % mywapt.wapt_repourl) logger.debug('WAPT base directory : %s' % mywapt.wapt_base_dir) logger.debug('Package cache dir : %s' % mywapt.packagecachedir) logger.debug('WAPT DB Structure version;: %s' % mywapt.waptdb.db_version) try: params_dict = {} try: params_dict = json.loads(options.params.replace("'", '"')) except: raise Exception('Install Parameters must be in json format') if action == 'install' or action == 'download': if len(args) < 2: print "You must provide at least one package name" sys.exit(1) if os.path.isdir(args[1]) or os.path.isfile(args[1]): print "installing WAPT file %s" % args[1] if action == 'install': mywapt.install_wapt(args[1], params_dict=params_dict) else: print "%sing WAPT packages %s" % (action, ','.join(args[1:])) if options.update_packages: print "Update package list" mywapt.update() result = mywapt.install( args[1:], force=options.force, params_dict=params_dict, download_only=(action == 'download'), ) print "\nResults :" if action <> 'download': for k in ('install', 'additional', 'upgrade', 'skipped', 'errors'): if result.get(k, []): print "\n=== %s packages ===\n%s" % ( k, '\n'.join([ " %-30s | %s (%s)" % (s[0], s[1].package, s[1].version) for s in result[k] ]), ) else: for k in ('downloaded', 'skipped', 'errors'): if result.get('downloads', { 'downloaded': [], 'skipped': [], 'errors': [] })[k]: print "\n=== %s packages ===\n%s" % ( k, '\n'.join([ " %s" % (s, ) for s in result['downloads'][k] ]), ) elif action == 'download': if len(args) < 2: print "You must provide at least one package name to download" sys.exit(1) if options.update_packages: print "Update package list" mywapt.update() print "Downloading packages %s" % (','.join(args[1:]), ) result = mywapt.download_packages(args[1:], usecache=not options.force) if result['downloaded']: print "\nDownloaded packages : \n%s" % "\n".join( [" %s" % p for p in result['downloaded']]) if result['skipped']: print "Skipped packages : \n%s" % "\n".join( [" %s" % p for p in result['skipped']]) if result['errors']: logger.critical('Unable to download some files : %s' % (result['errors'], )) sys.exit(1) elif action == 'show': if len(args) < 2: print "You must provide at least one package name to show" sys.exit(1) if os.path.isdir(args[1]) or os.path.isfile(args[1]): entry = PackageEntry().load_control_from_wapt(args[1]) print "%s" % entry else: print "Display package control data for %s\n" % (','.join( args[1:]), ) if options.update_packages: print "Update package list" mywapt.update() for packagename in args[1:]: entries = mywapt.waptdb.packages_matching(packagename) if entries: for e in entries: print "%s\n" % e.ascontrol( with_non_control_attributes=True) else: print "None packages found matching package name and version" elif action == 'show-params': if len(args) < 2: print "You must provide at one package name to show params for" sys.exit(1) for packagename in args[1:]: params = mywapt.waptdb.params(packagename) print "%s" % params elif action == 'list-registry': print "%-39s%-70s%-20s%-70s" % ('UninstallKey', 'Software', 'Version', 'Uninstallstring') print '-' * 39 + '-' * 70 + '-' * 20 + '-' * 70 for p in setuphelpers.installed_softwares(' '.join(args[1:])): print u"%-39s%-70s%-20s%-70s" % ( p['key'], p['name'], p['version'], p['uninstall_string']) elif action == 'showlog': if len(args) < 2: print "You must provide at least one package name" sys.exit(1) for packagename in args[1:]: result = mywapt.last_install_log(packagename) print "Package : %s\nStatus : %s\n\nInstallation log:\n%s" % ( packagename, result['status'], result['log']) elif action == 'remove': if len(args) < 2: print "You must provide at least one package name to remove" sys.exit(1) for packagename in args[1:]: print "Removing %s ..." % (packagename, ), mywapt.remove(packagename, force=options.force) print "done" elif action == 'session-setup': if len(args) < 2: print "You must provide at least one package to be configured in user's session" sys.exit(1) for packagename in args[1:]: print "Configuring %s ..." % (packagename, ), mywapt.session_setup(packagename, params_dict=params_dict) print "done" elif action == 'uninstall': # launch the setup.uninstall() procedure for the given packages # can be used when registering in registry a custom install with a python script if len(args) < 2: print "You must provide at least one package to be uninstalled" sys.exit(1) for packagename in args[1:]: print "uninstalling %s ..." % (packagename, ), mywapt.uninstall(packagename, params_dict=params_dict) print "uninstall done" elif action == 'update': print "Update package list" result = mywapt.update() print "Total packages : %i" % result['count'] print "Added packages : \n%s" % "\n".join( [" %s (%s)" % p for p in result['added']]) print "Removed packages : \n%s" % "\n".join( [" %s (%s)" % p for p in result['removed']]) print "Repositories URL : \n%s" % "\n".join( [" %s" % p for p in result['repos']]) elif action == 'upgradedb': (old, new) = mywapt.waptdb.upgradedb() if old == new: print "No database upgrade required, current %s, required %s" % ( old, mywapt.waptdb.curr_db_version) else: print "Old version : %s to new : %s" % (old, new) elif action == 'upgrade': if options.update_packages: print "Update package list" mywapt.update() result = mywapt.upgrade() if not result['install'] and not result[ 'additional'] and not result['upgrade'] and not result[ 'skipped']: print "Nothing to upgrade" else: for k in ('install', 'additional', 'upgrade', 'skipped', 'errors'): if result[k]: print "\n=== %s packages ===\n%s" % ( k, '\n'.join([ " %-30s | %s (%s)" % (s[0], s[1].package, s[1].version) for s in result[k] ]), ) sys.exit(0) elif action == 'list-upgrade': if options.update_packages: print "Update package list" mywapt.update() q = mywapt.list_upgrade() if not q: print "Nothing to upgrade" else: print ppdicttable([p[0] for p in q], [('package', 20), ('version', 10)]) elif action == 'download-upgrade': if options.update_packages: print "Update package list" mywapt.update() result = mywapt.download_upgrades() print "Downloaded packages : \n%s" % "\n".join( [" %s" % p for p in result['downloaded']]) print "Skipped packages : \n%s" % "\n".join( [" %s" % p for p in result['skipped']]) if result['errors']: logger.critical('Unable to download some files : %s' % (result['errors'], )) sys.exit(1) elif action == 'update-packages': if len(args) < 2: print "You must provide the directory" sys.exit(1) print update_packages(args[1]) elif action == 'sources': if len(args) < 2: print "You must provide the package name" sys.exit(1) os.startfile(mywapt.get_sources(args[1])) elif action == 'make-template': if len(args) < 2: print "You must provide the installer path" sys.exit(1) source_dir = mywapt.maketemplate(*args[1:]) print "Template created. You can build the WAPT package by launching\n %s build-package %s" % ( sys.argv[0], source_dir) os.startfile(source_dir) elif action == 'make-host-template': source_dir = mywapt.makehosttemplate(*args[1:]) print "Template created. You can build the WAPT package by launching\n %s build-package %s" % ( sys.argv[0], source_dir) os.startfile(source_dir) elif action == 'build-package': if len(args) < 2: print "You must provide at least one source directory for package build" sys.exit(1) for source_dir in [os.path.abspath(p) for p in args[1:]]: if os.path.isdir(source_dir): print('Building %s' % source_dir) result = mywapt.buildpackage( source_dir, inc_package_release=options.increlease, excludes=options.excludes.split(',')) package_fn = result['filename'] if package_fn: print "Package content:" for f in result['files']: print " %s" % f[0] print('...done. Package filename %s' % (package_fn, )) def pwd_callback(*args): """Default password callback for opening private keys""" return open(options.private_key_passwd, 'r').read() if mywapt.private_key: print('Signing %s' % package_fn) if options.private_key_passwd: signature = mywapt.signpackage( package_fn, excludes=options.excludes.split(','), callback=pwd_callback) else: signature = mywapt.signpackage( package_fn, excludes=options.excludes.split(',')) print "Package %s signed : signature :\n%s" % ( package_fn, signature) else: logger.warning( 'No private key provided, package %s is unsigned !' % package_fn) if mywapt.upload_cmd: print '\nYou can upload to repository with\n %s upload-package %s ' % ( sys.argv[0], package_fn) return 0 else: logger.critical('package not created') return 1 else: logger.critical('Directory %s not found' % source_dir) elif action == 'sign-package': if len(args) < 2: print "You must provide at least one source directory or package to sign" sys.exit(1) for waptfile in [os.path.abspath(p) for p in args[1:]]: if os.path.isdir(waptfile) or os.path.isfile(waptfile): print('Signing %s' % waptfile) signature = mywapt.signpackage( waptfile, excludes=options.excludes.split(',')) print "Package %s signed : signature :\n%s" % (waptfile, signature) else: logger.critical('Package %s not found' % waptfile) return 1 elif action == 'upload-package': if len(args) < 2: print "You must provide a package to upload" sys.exit(1) waptfiles = [] for a in args[1:]: waptfiles += glob.glob(a) waptfile_arg = " ".join(['"%s"' % f for f in waptfiles]) print setuphelpers.run(mywapt.upload_cmd % {'waptfile': waptfile_arg}) if mywapt.after_upload: print setuphelpers.run(mywapt.after_upload % {'waptfile': waptfile_arg}) elif action == 'search': if options.update_packages: print "Update package list" mywapt.update() result = mywapt.waptdb.packages_search(args[1:]) print ppdicttable(result, (('package', 30), ('version', 10), ('description', 80))) elif action == 'cleanup': result = mywapt.cleanup() print "Removed files : \n%s" % "\n".join( [" %s" % p for p in result]) elif action == 'inventory': print mywapt.inventory() elif action == 'setup-tasks': print mywapt.setup_tasks() elif action == 'list': def cb(fieldname, value): if value and fieldname == 'install_date': return value[0:16] else: return value print ppdicttable( mywapt.waptdb.installed_search(args[1:]).values(), (('package', 20), ('version', 15), ('install_status', 10), ('install_date', 16), ('description', 80)), callback=cb) else: print 'Unknown action %s' % action sys.exit(1) except Exception, e: print "FATAL ERROR : %s" % e if logger.level == logging.DEBUG: raise sys.exit(3)