text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> compile all the executable and the arguments, combining with common arguments <END_TASK> <USER_TASK:> Description: def _get_args(self, executable, *args): """compile all the executable and the arguments, combining with common arguments to create a full batch of command args"""
args = list(args) args.insert(0, executable) if self.username: args.append("--username={}".format(self.username)) if self.host: args.append("--host={}".format(self.host)) if self.port: args.append("--port={}".format(self.port)) args.append(self.dbname) #args.extend(other_args) return args
<SYSTEM_TASK:> return the path for a file we can use to back up the table <END_TASK> <USER_TASK:> Description: def _get_outfile_path(self, table): """return the path for a file we can use to back up the table"""
self.outfile_count += 1 outfile = os.path.join(self.directory, '{:03d}_{}.sql.gz'.format(self.outfile_count, table)) return outfile
<SYSTEM_TASK:> run the queries <END_TASK> <USER_TASK:> Description: def _run_queries(self, queries, *args, **kwargs): """run the queries queries -- list -- the queries to run return -- string -- the results of the query? """
# write out all the commands to a temp file and then have psql run that file f = self._get_file() for q in queries: f.write("{};\n".format(q)) f.close() psql_args = self._get_args('psql', '-X', '-f {}'.format(f.name)) return self._run_cmd(' '.join(psql_args), *args, **kwargs)
<SYSTEM_TASK:> restore the auto increment value for the table to what it was previously <END_TASK> <USER_TASK:> Description: def _restore_auto_increment(self, table): """restore the auto increment value for the table to what it was previously"""
query, seq_table, seq_column, seq_name = self._get_auto_increment_info(table) if query: queries = [query, "select nextval('{}')".format(seq_name)] return self._run_queries(queries)
<SYSTEM_TASK:> figure out the the autoincrement value for the given table <END_TASK> <USER_TASK:> Description: def _get_auto_increment_info(self, table): """figure out the the autoincrement value for the given table"""
query = '' seq_table = '' seq_column = '' seq_name = '' find_query = "\n".join([ "SELECT", " t.relname as related_table,", " a.attname as related_column,", " s.relname as sequence_name", "FROM pg_class s", "JOIN pg_depend d ON d.objid = s.oid", "JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid", "JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)", "JOIN pg_namespace n ON n.oid = s.relnamespace", "WHERE", " s.relkind = 'S'", "AND", " n.nspname = 'public'", "AND", " t.relname = '{}'".format(table) ]) pipe = self._run_queries([find_query], popen_kwargs={'stdout': subprocess.PIPE}) stdout, stderr = pipe.communicate() if stdout: try: m = re.findall('^\s*(\S+)\s*\|\s*(\S+)\s*\|\s*(\S+)\s*$', stdout, flags=re.MULTILINE) seq_table, seq_column, seq_name = m[1] # http://www.postgresql.org/docs/9.2/static/functions-sequence.html # http://www.postgresql.org/docs/9.2/static/functions-conditional.html query = "\n".join([ "SELECT", " setval('{}',".format(seq_name.strip()), " coalesce(max({}), 1),".format(seq_column.strip()), " max({}) IS NOT null)".format(seq_column.strip()), "FROM \"{}\"".format(seq_table.strip()) ]) except IndexError: query = '' return query, seq_table, seq_column, seq_name
<SYSTEM_TASK:> use the self.directory to restore a db <END_TASK> <USER_TASK:> Description: def restore(self): """use the self.directory to restore a db NOTE -- this will only restore a database dumped with one of the methods of this class """
sql_files = [] for root, dirs, files in os.walk(self.directory): for f in files: if f.endswith(".sql.gz"): path = os.path.join(self.directory, f) self._run_cmd(["gunzip", path]) sql_files.append(f.rstrip(".gz")) elif f.endswith('.sql'): sql_files.append(f) sql_files.sort() # we want to go in the order the tables were dumped r = re.compile('\d{3,}_([^\.]+)') for f in sql_files: path = os.path.join(self.directory, f) m = r.match(f) if m: table = m.group(1) logger.info('------- restoring table {}'.format(table)) #psql_args = self._get_args('psql', '-X', '--echo-queries', '-f {}'.format(path)) psql_args = self._get_args('psql', '-X', '--quiet', '--file={}'.format(path)) self._run_cmd(psql_args) logger.info('------- restored table {}'.format(table)) return True
<SYSTEM_TASK:> this returns an environment dictionary we want to use to run the command <END_TASK> <USER_TASK:> Description: def _get_env(self): """this returns an environment dictionary we want to use to run the command this will also create a fake pgpass file in order to make it possible for the script to be passwordless"""
if hasattr(self, 'env'): return self.env # create a temporary pgpass file pgpass = self._get_file() # format: http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html pgpass.write('*:*:*:{}:{}\n'.format(self.username, self.password).encode("utf-8")) pgpass.close() self.env = dict(os.environ) self.env['PGPASSFILE'] = pgpass.name # we want to assure a consistent environment if 'PGOPTIONS' in self.env: del self.env['PGOPTIONS'] return self.env
<SYSTEM_TASK:> Get a template response <END_TASK> <USER_TASK:> Description: def _get_response(**kwargs): """Get a template response Use kwargs to add things to the dictionary """
if 'code' not in kwargs: kwargs['code'] = 200 if 'headers' not in kwargs: kwargs['headers'] = dict() if 'version' not in kwargs: kwargs['version'] = 'HTTP/1.1' return dict(**kwargs)
<SYSTEM_TASK:> Convenience function to write to the transport <END_TASK> <USER_TASK:> Description: def _write_transport(self, string): """Convenience function to write to the transport"""
if isinstance(string, str): # we need to convert to bytes self.transport.write(string.encode('utf-8')) else: self.transport.write(string)
<SYSTEM_TASK:> Write the response back to the client <END_TASK> <USER_TASK:> Description: def _write_response(self, response): """Write the response back to the client Arguments: response -- the dictionary containing the response. """
status = '{} {} {}\r\n'.format(response['version'], response['code'], responses[response['code']]) self.logger.debug("Responding status: '%s'", status.strip()) self._write_transport(status) if 'body' in response and 'Content-Length' not in response['headers']: response['headers']['Content-Length'] = len(response['body']) response['headers']['Date'] = datetime.utcnow().strftime( "%a, %d %b %Y %H:%M:%S +0000") for (header, content) in response['headers'].items(): self.logger.debug("Sending header: '%s: %s'", header, content) self._write_transport('{}: {}\r\n'.format(header, content)) self._write_transport('\r\n') if 'body' in response: self._write_transport(response['body'])
<SYSTEM_TASK:> Called when the connection is made <END_TASK> <USER_TASK:> Description: def connection_made(self, transport): """Called when the connection is made"""
self.logger.info('Connection made at object %s', id(self)) self.transport = transport self.keepalive = True if self._timeout: self.logger.debug('Registering timeout event') self._timout_handle = self._loop.call_later( self._timeout, self._handle_timeout)
<SYSTEM_TASK:> Called when the connection is lost or closed. <END_TASK> <USER_TASK:> Description: def connection_lost(self, exception): """Called when the connection is lost or closed. The argument is either an exception object or None. The latter means a regular EOF is received, or the connection was aborted or closed by this side of the connection. """
if exception: self.logger.exception('Connection lost!') else: self.logger.info('Connection lost')
<SYSTEM_TASK:> Process received data from the socket <END_TASK> <USER_TASK:> Description: def data_received(self, data): """Process received data from the socket Called when we receive data """
self.logger.debug('Received data: %s', repr(data)) try: request = self._parse_headers(data) self._handle_request(request) except InvalidRequestError as e: self._write_response(e.get_http_response()) if not self.keepalive: if self._timeout_handle: self._timeout_handle.cancel() self.transport.close() if self._timeout and self._timeout_handle: self.logger.debug('Delaying timeout event') self._timeout_handle.cancel() self._timout_handle = self._loop.call_later( self._timeout, self._handle_timeout)
<SYSTEM_TASK:> Parse the request URI into something useful <END_TASK> <USER_TASK:> Description: def _get_request_uri(self, request): """Parse the request URI into something useful Server MUST accept full URIs (5.1.2)"""
request_uri = request['target'] if request_uri.startswith('/'): # eg. GET /index.html return (request.get('Host', 'localhost').split(':')[0], request_uri[1:]) elif '://' in request_uri: # eg. GET http://rded.nl locator = request_uri.split('://', 1)[1] host, path = locator.split('/', 1) return (host.split(':')[0], path)
<SYSTEM_TASK:> Process the headers and get the file <END_TASK> <USER_TASK:> Description: def _handle_request(self, request): """Process the headers and get the file"""
# Check if this is a persistent connection. if request['version'] == 'HTTP/1.1': self.keepalive = not request.get('Connection') == 'close' elif request['version'] == 'HTTP/1.0': self.keepalive = request.get('Connection') == 'Keep-Alive' # Check if we're getting a sane request if request['method'] not in ('GET'): raise InvalidRequestError(501, 'Method not implemented') if request['version'] not in ('HTTP/1.0', 'HTTP/1.1'): raise InvalidRequestError( 505, 'Version not supported. Supported versions are: {}, {}' .format('HTTP/1.0', 'HTTP/1.1')) host, location = self._get_request_uri(request) # We must ignore the Host header if a host is specified in GET if host is None: host = request.get('Host') # Check if this request is intended for this webserver if host is not None and not host == self.host: self.logger.info('Got a request for unknown host %s', host) raise InvalidRequestError(404, "We don't serve this host") filename = os.path.join(self.folder, unquote(location)) self.logger.debug('trying to serve %s', filename) if os.path.isdir(filename): filename = os.path.join(filename, 'index.html') if not os.path.isfile(filename): raise InvalidRequestError(404, 'Not Found') # Start response with version response = _get_response(version=request['version']) # timeout negotiation match = re.match(r'timeout=(\d+)', request.get('Keep-Alive', '')) if match is not None: requested_timeout = int(match.group(1)) if requested_timeout < self._timeout: self._timeout = requested_timeout # tell the client our timeout if self.keepalive: response['headers'][ 'Keep-Alive'] = 'timeout={}'.format(self._timeout) # Set Content-Type response['headers']['Content-Type'] = mimetypes.guess_type( filename)[0] or 'text/plain' # Generate E-tag sha1 = hashlib.sha1() with open(filename, 'rb') as fp: response['body'] = fp.read() sha1.update(response['body']) etag = sha1.hexdigest() # Create 304 response if if-none-match matches etag if request.get('If-None-Match') == '"{}"'.format(etag): # 304 responses shouldn't contain many headers we might already # have added. response = _get_response(code=304) response['headers']['Etag'] = '"{}"'.format(etag) self._write_response(response)
<SYSTEM_TASK:> Get this exception as an HTTP response suitable for output <END_TASK> <USER_TASK:> Description: def get_http_response(self): """Get this exception as an HTTP response suitable for output"""
return _get_response( code=self.code, body=str(self), headers={ 'Content-Type': 'text/plain' } )
<SYSTEM_TASK:> Run the HTTP server <END_TASK> <USER_TASK:> Description: def run(argv=None): # pragma: no cover """Run the HTTP server Usage: httpserver [options] [<folder>] Options:: -h,--host=<hostname> What host name to serve (default localhost) -a,--bindaddress=<address> Address to bind to (default 127.0.0.1) -p,--port=<port> Port to listen on (default 8080) -v,--verbose Increase verbosity to INFO messages -d,--debug Increase verbosity to DEBUG messages --help Print this help message --version Print the version To serve /path/to/www on all (ipv4) addresses for host myserver on port 80:: httpserver -a 0.0.0.0 -p 80 -h myserver /path/to/www """
import sys import os import docopt import textwrap # Check for the version if not sys.version_info >= (3, 4): print('This python version is not supported. Please use python 3.4') exit(1) argv = argv or sys.argv[1:] # remove some RST formatting docblock = run.__doc__.replace('::', ':') args = docopt.docopt(textwrap.dedent(docblock), argv) if args['--version']: print("httpserver version {} by {}".format( __version__, __author__)) exit(0) # Set up logging level = logging.WARNING if args['--verbose']: level = logging.INFO if args['--debug']: level = logging.DEBUG logging.basicConfig(level=level) logger = logging.getLogger('run method') logger.debug('CLI args: %s' % args) bindaddr = args['--bindaddress'] or '127.0.0.1' port = args['--port'] or '8080' folder = args['<folder>'] or os.getcwd() hostname = args['--host'] or 'localhost' _start_server(bindaddr, port, hostname, folder)
<SYSTEM_TASK:> Open url and read <END_TASK> <USER_TASK:> Description: def reading(self): """Open url and read """
try: # testing proxy proxies = {} try: proxies["http_proxy"] = os.environ['http_proxy'] except KeyError: pass try: proxies["https_proxy"] = os.environ['https_proxy'] except KeyError: pass if len(proxies) != 0: proxy = urllib2.ProxyHandler(proxies) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) # end testing f = urllib2.urlopen(self.link) return f.read() except (urllib2.URLError, ValueError): print("\n{0}Can't read the file '{1}'{2}".format( self.meta.color["RED"], self.link.split("/")[-1], self.meta.color["ENDC"])) return " "
<SYSTEM_TASK:> View or enabled or disabled repositories <END_TASK> <USER_TASK:> Description: def repos(self): """View or enabled or disabled repositories """
def_cnt, cus_cnt = 0, 0 print("") self.msg.template(78) print("{0}{1}{2}{3}{4}{5}{6}".format( "| Repo id", " " * 2, "Repo URL", " " * 44, "Default", " " * 3, "Status")) self.msg.template(78) for repo_id, repo_URL in sorted(self.all_repos.iteritems()): status, COLOR = "disabled", self.meta.color["RED"] default = "yes" if len(repo_URL) > 49: repo_URL = repo_URL[:48] + "~" if repo_id in self.meta.repositories: def_cnt += 1 status, COLOR = "enabled", self.meta.color["GREEN"] if repo_id not in self.meta.default_repositories: cus_cnt += 1 default = "no" print(" {0}{1}{2}{3}{4}{5}{6}{7:>8}{8}".format( repo_id, " " * (9 - len(repo_id)), repo_URL, " " * (52 - len(repo_URL)), default, " " * (8 - len(default)), COLOR, status, self.meta.color["ENDC"])) print("\nRepositories summary") print("=" * 79) print("{0}{1}/{2} enabled default repositories and {3} custom.".format( self.meta.color["GREY"], def_cnt, len(self.all_repos), cus_cnt)) print("Edit the file '/etc/slpkg/repositories.conf' for enable " "and disable default\nrepositories or run 'slpkg " "repo-enable' command.\n{0}".format(self.meta.color["ENDC"])) raise SystemExit()
<SYSTEM_TASK:> Create dictionary from list with key in lower case <END_TASK> <USER_TASK:> Description: def case_sensitive(self, lst): """Create dictionary from list with key in lower case and value with default """
dictionary = {} for pkg in lst: dictionary[pkg.lower()] = pkg return dictionary
<SYSTEM_TASK:> Remove double item from list <END_TASK> <USER_TASK:> Description: def remove_dbs(self, double): """Remove double item from list """
one = [] for dup in double: if dup not in one: one.append(dup) return one
<SYSTEM_TASK:> Returns list with all the names of packages repository <END_TASK> <USER_TASK:> Description: def package_name(self, PACKAGES_TXT): """Returns list with all the names of packages repository """
packages = [] for line in PACKAGES_TXT.splitlines(): if line.startswith("PACKAGE NAME:"): packages.append(split_package(line[14:].strip())[0]) return packages
<SYSTEM_TASK:> Check if files downloaded and return downloaded <END_TASK> <USER_TASK:> Description: def check_downloaded(self, path, maybe_downloaded): """Check if files downloaded and return downloaded packages """
downloaded = [] for pkg in maybe_downloaded: if os.path.isfile(path + pkg): downloaded.append(pkg) return downloaded
<SYSTEM_TASK:> Generate graph file with depenndencies map tree <END_TASK> <USER_TASK:> Description: def dependencies(self, deps_dict): """Generate graph file with depenndencies map tree """
try: import pygraphviz as pgv except ImportError: graph_easy, comma = "", "" if (self.image == "ascii" and not os.path.isfile("/usr/bin/graph-easy")): comma = "," graph_easy = " graph-easy" print("Require 'pygraphviz{0}{1}': Install with 'slpkg -s sbo " "pygraphviz{1}'".format(comma, graph_easy)) raise SystemExit() if self.image != "ascii": self.check_file() try: G = pgv.AGraph(deps_dict) G.layout(prog="fdp") if self.image == "ascii": G.write("{0}.dot".format(self.image)) self.graph_easy() G.draw(self.image) except IOError: raise SystemExit() if os.path.isfile(self.image): print("Graph image file '{0}' created".format(self.image)) raise SystemExit()
<SYSTEM_TASK:> Check for file format and type <END_TASK> <USER_TASK:> Description: def check_file(self): """Check for file format and type """
try: image_type = ".{0}".format(self.image.split(".")[1]) if image_type not in self.file_format: print("Format: '{0}' not recognized. Use one of " "them:\n{1}".format(self.image.split(".")[1], ", ".join(self.file_format))) raise SystemExit() except IndexError: print("slpkg: Error: Image file suffix missing") raise SystemExit()
<SYSTEM_TASK:> This filter avoid list double packages from <END_TASK> <USER_TASK:> Description: def alien_filter(packages, sizes): """This filter avoid list double packages from alien repository """
cache, npkg, nsize = [], [], [] for p, s in zip(packages, sizes): name = split_package(p)[0] if name not in cache: cache.append(name) npkg.append(p) nsize.append(s) return npkg, nsize
<SYSTEM_TASK:> Manage removed packages by extra options <END_TASK> <USER_TASK:> Description: def _get_removed(self): """Manage removed packages by extra options """
removed, packages = [], [] if "--tag" in self.extra: for pkg in find_package("", self.meta.pkg_path): for tag in self.binary: if pkg.endswith(tag): removed.append(split_package(pkg)[0]) packages.append(pkg) if not removed: self.msg.pkg_not_found("", "'tag'", "Can't remove", "\n") raise SystemExit(1) else: for pkg in self.binary: name = GetFromInstalled(pkg).name() ver = GetFromInstalled(pkg).version() package = find_package("{0}{1}{2}".format( name, ver, self.meta.sp), self.meta.pkg_path) if pkg and name == pkg: removed.append(pkg) packages.append(package[0]) else: self.msg.pkg_not_found("", pkg, "Can't remove", "\n") raise SystemExit(1) return removed, packages
<SYSTEM_TASK:> View packages before removed <END_TASK> <USER_TASK:> Description: def _view_removed(self): """View packages before removed """
print("\nPackages with name matching [ {0}{1}{2} ]\n".format( self.meta.color["CYAN"], ", ".join(self.binary), self.meta.color["ENDC"])) removed, packages = self._get_removed() if packages and "--checklist" in self.extra: removed = [] text = "Press 'spacebar' to unchoose packages from the remove" backtitle = "{0} {1}".format(self.meta.__all__, self.meta.__version__) status = True pkgs = DialogUtil(packages, text, " Remove ", backtitle, status).checklist() if pkgs: for rmv in pkgs: removed.append(split_package(rmv)[0]) self.meta.default_answer = "y" else: for rmv, pkg in zip(removed, packages): print("[ {0}delete{1} ] --> {2}".format( self.meta.color["RED"], self.meta.color["ENDC"], pkg)) self._sizes(pkg) self._calc_sizes() self._remove_summary() return removed
<SYSTEM_TASK:> View dependencies before remove <END_TASK> <USER_TASK:> Description: def _view_deps(self, path, package): """View dependencies before remove """
self.size = 0 packages = [] dependencies = (Utils().read_file(path + package)).splitlines() for dep in dependencies: if GetFromInstalled(dep).name(): ver = GetFromInstalled(dep).version() packages.append(dep + ver) else: dependencies.remove(dep) if packages: if "--checklist" in self.extra: deps, dependencies = [], [] text = "Found dependencies for the package {0}".format(package) backtitle = "{0} {1}".format(self.meta.__all__, self.meta.__version__) status = True deps = DialogUtil(packages, text, " Remove ", backtitle, status).checklist() for d in deps: dependencies.append("-".join(d.split("-")[:-1])) self.meta.remove_deps_answer = "y" else: print("") # new line at start self.msg.template(78) print("| Found dependencies for the package {0}:".format( package)) self.msg.template(78) for pkg in packages: find = find_package(pkg + self.meta.sp, self.meta.pkg_path) self._sizes(find[0]) print("| {0}{1}{2}".format(self.meta.color["RED"], pkg, self.meta.color["ENDC"])) self.msg.template(78) self._calc_sizes() print("| {0}Size of removed dependencies {1} {2}{3}".format( self.meta.color["GREY"], round(self.size, 2), self.unit, self.meta.color["ENDC"])) self.msg.template(78) return dependencies
<SYSTEM_TASK:> Skip packages from remove <END_TASK> <USER_TASK:> Description: def _skip_remove(self): """Skip packages from remove """
if "--checklist" not in self.extra: self.msg.template(78) print("| Insert packages to exception remove:") self.msg.template(78) try: self.skip = raw_input(" > ").split() except EOFError: print("") raise SystemExit() for s in self.skip: if s in self.removed: self.removed.remove(s)
<SYSTEM_TASK:> Check package if dependencies for another package <END_TASK> <USER_TASK:> Description: def _check_if_used(self, removes): """Check package if dependencies for another package before removed"""
if "--check-deps" in self.extra: package, dependency, pkg_dep = [], [], [] for pkg in find_package("", self.dep_path): deps = Utils().read_file(self.dep_path + pkg) for rmv in removes: if GetFromInstalled(rmv).name() and rmv in deps.split(): pkg_dep.append( "{0} is dependency of the package --> {1}".format( rmv, pkg)) package.append(pkg) dependency.append(rmv) if package: if "--checklist" in self.extra: text = ("Press 'spacebar' to choose packages for the remove" " exception") backtitle = "{0} {1}".format(self.meta.__all__, self.meta.__version__) status = False choose = DialogUtil(pkg_dep, text, " !!! WARNING !!! ", backtitle, status).checklist() for pkg in choose: self.skip.append(pkg.split()[0]) else: self.msg.template(78) print("| {0}{1}{2}".format( self.meta.color["RED"], " " * 30 + "!!! WARNING !!!", self.meta.color["ENDC"])) self.msg.template(78) for p, d in zip(package, dependency): print("| {0}{1}{2} is dependency of the package --> " "{3}{4}{5}".format(self.meta.color["YELLOW"], d, self.meta.color["ENDC"], self.meta.color["GREEN"], p, self.meta.color["ENDC"])) self.msg.template(78) self._skip_remove()
<SYSTEM_TASK:> Prints all removed packages <END_TASK> <USER_TASK:> Description: def _reference_rmvs(self, removes): """Prints all removed packages """
print("") self.msg.template(78) msg_pkg = "package" if len(removes) > 1: msg_pkg = "packages" print("| Total {0} {1} removed".format(len(removes), msg_pkg)) self.msg.template(78) for pkg in removes: if not GetFromInstalled(pkg).name(): print("| Package {0} removed".format(pkg)) else: print("| Package {0} not found".format(pkg)) self.msg.template(78) print("")
<SYSTEM_TASK:> Find installed Slackware packages <END_TASK> <USER_TASK:> Description: def find(self, flag): """Find installed Slackware packages """
matching, pkg_cache, match_cache = 0, "", "" print("\nPackages with matching name [ {0}{1}{2} ]\n".format( self.meta.color["CYAN"], ", ".join(self.binary), self.meta.color["ENDC"])) for pkg in self.binary: for match in find_package("", self.meta.pkg_path): if "--case-ins" in flag: pkg_cache = pkg.lower() match_cache = match.lower() else: pkg_cache = pkg match_cache = match if pkg_cache in match_cache: matching += 1 self._sizes(match) print("[ {0}installed{1} ] [ {2} ] - {3}".format( self.meta.color["GREEN"], self.meta.color["ENDC"], self.file_size, match)) if matching == 0: message = "Can't find" self.msg.pkg_not_found("", ", ".join(self.binary), message, "\n") raise SystemExit(1) else: self._calc_sizes() print("\nFound summary") print("=" * 79) print("{0}Total found {1} matching packages.{2}".format( self.meta.color["GREY"], matching, self.meta.color["ENDC"])) print("{0}Size of installed packages {1} {2}.{3}\n".format( self.meta.color["GREY"], round(self.size, 2), self.unit, self.meta.color["ENDC"]))
<SYSTEM_TASK:> Print the Slackware packages contents <END_TASK> <USER_TASK:> Description: def display(self): """Print the Slackware packages contents """
for pkg in self.binary: name = GetFromInstalled(pkg).name() ver = GetFromInstalled(pkg).version() find = find_package("{0}{1}{2}".format(name, ver, self.meta.sp), self.meta.pkg_path) if find: package = Utils().read_file( self.meta.pkg_path + "".join(find)) print(package) else: message = "Can't dislpay" if len(self.binary) > 1: bol = eol = "" else: bol = eol = "\n" self.msg.pkg_not_found(bol, pkg, message, eol) raise SystemExit(1)
<SYSTEM_TASK:> List with the installed packages <END_TASK> <USER_TASK:> Description: def package_list(self, repo, name, INDEX, installed): """List with the installed packages """
tty_size = os.popen("stty size", "r").read().split() row = int(tty_size[0]) - 2 try: all_installed_names = [] index, page, pkg_list = 0, row, [] r = self.list_lib(repo) pkg_list = self.list_greps(repo, r)[0] all_installed_names = self.list_of_installed(repo, name) print("") for pkg in sorted(pkg_list): pkg = self._splitting_packages(pkg, repo, name) if installed: if repo == "sbo": if pkg in all_installed_names: pkg = ("{0}{1}{2}".format(self.meta.color["GREEN"], pkg, self.meta.color["ENDC"])) else: if pkg in all_installed_names: pkg = ("{0}{1}{2}".format(self.meta.color["GREEN"], pkg, self.meta.color["ENDC"])) if INDEX: index += 1 pkg = self.list_color_tag(pkg) print("{0}{1}:{2} {3}".format( self.meta.color["GREY"], index, self.meta.color["ENDC"], pkg)) if index == page: read = raw_input("\nPress {0}Enter{1} to " "continue... ".format( self.meta.color["CYAN"], self.meta.color["ENDC"])) if read in ["Q", "q"]: break print("") # new line after page page += row else: print(pkg) print("") # new line at end except EOFError: print("") # new line at exit raise SystemExit()
<SYSTEM_TASK:> Return package name from repositories <END_TASK> <USER_TASK:> Description: def _splitting_packages(self, pkg, repo, name): """Return package name from repositories """
if name and repo != "sbo": pkg = split_package(pkg)[0] elif not name and repo != "sbo": pkg = pkg[:-4] return pkg
<SYSTEM_TASK:> Tag with color installed packages <END_TASK> <USER_TASK:> Description: def list_color_tag(self, pkg): """Tag with color installed packages """
name = GetFromInstalled(pkg).name() find = name + self.meta.sp if pkg.endswith(".txz") or pkg.endswith(".tgz"): find = pkg[:-4] if find_package(find, self.meta.pkg_path): pkg = "{0}{1}{2}".format(self.meta.color["GREEN"], pkg, self.meta.color["ENDC"]) return pkg
<SYSTEM_TASK:> Return installed packages <END_TASK> <USER_TASK:> Description: def list_of_installed(self, repo, name): """Return installed packages """
all_installed_names = [] all_installed_packages = find_package("", self.meta.pkg_path) for inst in all_installed_packages: if repo == "sbo" and inst.endswith("_SBo"): name = split_package(inst)[0] all_installed_names.append(name) else: if name: all_installed_names.append(split_package(inst)[0]) else: all_installed_names.append(inst) return all_installed_names
<SYSTEM_TASK:> Filter rlw repository data <END_TASK> <USER_TASK:> Description: def rlw_filter(name, location, size, unsize): """Filter rlw repository data """
arch = _meta_.arch if arch.startswith("i") and arch.endswith("86"): arch = "i486" (fname, flocation, fsize, funsize) = ([] for i in range(4)) for n, l, s, u in zip(name, location, size, unsize): loc = l.split("/") if arch == loc[-1]: fname.append(n) flocation.append(l) fsize.append(s) funsize.append(u) return [fname, flocation, fsize, funsize]
<SYSTEM_TASK:> Fix to avoid packages include in slackbuilds folder <END_TASK> <USER_TASK:> Description: def alien_filter(name, location, size, unsize): """Fix to avoid packages include in slackbuilds folder """
(fname, flocation, fsize, funsize) = ([] for i in range(4)) for n, l, s, u in zip(name, location, size, unsize): if "slackbuilds" != l: fname.append(n) flocation.append(l) fsize.append(s) funsize.append(u) return [fname, flocation, fsize, funsize]
<SYSTEM_TASK:> Filter Alien"s repository data <END_TASK> <USER_TASK:> Description: def rested_filter(name, location, size, unsize): """Filter Alien"s repository data """
ver = slack_ver() if _meta_.slack_rel == "current": ver = "current" path_pkg = "pkg" if _meta_.arch == "x86_64": path_pkg = "pkg64" (fname, flocation, fsize, funsize) = ([] for i in range(4)) for n, l, s, u in zip(name, location, size, unsize): if path_pkg == l.split("/")[-2] and ver == l.split("/")[-1]: fname.append(n) flocation.append(l) fsize.append(s) funsize.append(u) return [fname, flocation, fsize, funsize]
<SYSTEM_TASK:> Grap package requirements from repositories <END_TASK> <USER_TASK:> Description: def get_deps(self): """Grap package requirements from repositories """
if self.repo == "rlw": dependencies = {} rlw_deps = Utils().read_file(_meta_.conf_path + "rlworkman.deps") for line in rlw_deps.splitlines(): if line and not line.startswith("#"): pkgs = line.split(":") dependencies[pkgs[0]] = pkgs[1] if self.name in dependencies.keys(): return dependencies[self.name].split() else: return "" else: PACKAGES_TXT = Utils().read_file("{0}{1}_repo/PACKAGES.TXT".format( _meta_.lib_path, self.repo)) for line in PACKAGES_TXT.splitlines(): if line.startswith("PACKAGE NAME:"): pkg_name = split_package(line[14:].strip())[0] if line.startswith("PACKAGE REQUIRED:"): if pkg_name == self.name: if line[18:].strip(): return self._req_fix(line)
<SYSTEM_TASK:> Fix slacky and salix requirements because many dependencies splitting <END_TASK> <USER_TASK:> Description: def _req_fix(self, line): """Fix slacky and salix requirements because many dependencies splitting with "," and others with "|" """
deps = [] for dep in line[18:].strip().split(","): dep = dep.split("|") if self.repo == "slacky": if len(dep) > 1: for d in dep: deps.append(d.split()[0]) dep = "".join(dep) deps.append(dep.split()[0]) else: if len(dep) > 1: for d in dep: deps.append(d) deps.append(dep[0]) return deps
<SYSTEM_TASK:> Choose what do to file by file <END_TASK> <USER_TASK:> Description: def question(self, n): """Choose what do to file by file """
print("") prompt_ask = raw_input("{0} [K/O/R/D/M/Q]? ".format(n)) print("") if prompt_ask in ("K", "k"): self.keep() elif prompt_ask in ("O", "o"): self._overwrite(n) elif prompt_ask in ("R", "r"): self._remove(n) elif prompt_ask in ("D", "d"): self.diff(n) self.i -= 1 elif prompt_ask in ("M", "m"): self.merge(n) elif prompt_ask in ("Q", "q", "quit"): self.quit()
<SYSTEM_TASK:> Remove one single file <END_TASK> <USER_TASK:> Description: def _remove(self, n): """Remove one single file """
if os.path.isfile(n): os.remove(n) if not os.path.isfile(n): print("File '{0}' removed".format(n))
<SYSTEM_TASK:> Overwrite old file with new and keep file with suffix .old <END_TASK> <USER_TASK:> Description: def _overwrite(self, n): """Overwrite old file with new and keep file with suffix .old """
if os.path.isfile(n[:-4]): shutil.copy2(n[:-4], n[:-4] + ".old") print("Old file {0} saved as {1}.old".format( n[:-4].split("/")[-1], n[:-4].split("/")[-1])) if os.path.isfile(n): shutil.move(n, n[:-4]) print("New file {0} overwrite as {1}".format( n.split("/")[-1], n[:-4].split("/")[-1]))
<SYSTEM_TASK:> Print the differences between the two files <END_TASK> <USER_TASK:> Description: def diff(self, n): """Print the differences between the two files """
if os.path.isfile(n[:-4]): diff1 = Utils().read_file(n[:-4]).splitlines() if os.path.isfile(n): diff2 = Utils().read_file(n).splitlines() lines, l, c = [], 0, 0 for a, b in itertools.izip_longest(diff1, diff2): l += 1 if a != b: for s1, s2 in itertools.izip_longest(str(a), str(b)): c += 1 if s1 != s2: break print("@@ -{0},{1} +{2},{3} @@\n".format(l, c, l, c)) for line in lines[-3:]: print("{0}".format(line)) if a is None: a = "" print("{0}{1}{2}{3}".format(self.red, "-", self.endc, a)) if b is None: b = "" print("{0}{1}{2}{3}".format(self.green, "+", self.endc, b)) lines = [] c = 0 else: lines.append(a)
<SYSTEM_TASK:> Matching packages distinguish between uppercase and <END_TASK> <USER_TASK:> Description: def sbo_case_insensitive(self): """Matching packages distinguish between uppercase and lowercase for sbo repository """
if "--case-ins" in self.flag: data = SBoGrep(name="").names() data_dict = Utils().case_sensitive(data) for key, value in data_dict.iteritems(): if key == self.name.lower(): self.name = value
<SYSTEM_TASK:> Check if dependencies used <END_TASK> <USER_TASK:> Description: def check_used(self, pkg): """Check if dependencies used """
used = [] dep_path = self.meta.log_path + "dep/" logs = find_package("", dep_path) for log in logs: deps = Utils().read_file(dep_path + log) for dep in deps.splitlines(): if pkg == dep: used.append(log) return used
<SYSTEM_TASK:> Return version from installed packages <END_TASK> <USER_TASK:> Description: def version(self): """Return version from installed packages """
if self.find: return self.meta.sp + split_package(self.find)[1] return ""
<SYSTEM_TASK:> Check from GitHub slpkg repository if new version is available <END_TASK> <USER_TASK:> Description: def it_self_update(): """Check from GitHub slpkg repository if new version is available download and update itself """
__new_version__ = "" repository = "gitlab" branch = "master" ver_link = ("https://raw.{0}usercontent.com/{1}/{2}/" "{3}/{4}/__metadata__.py".format(repository, _meta_.__author__, _meta_.__all__, branch, _meta_.__all__)) version_data = URL(ver_link).reading() for line in version_data.splitlines(): line = line.strip() if line.startswith("__version_info__"): __new_version__ = ".".join(re.findall(r"\d+", line)) if __new_version__ > _meta_.__version__: if _meta_.default_answer in ["y", "Y"]: answer = _meta_.default_answer else: print("\nNew version '{0}-{1}' is available !\n".format( _meta_.__all__, __new_version__)) try: answer = raw_input("Would you like to upgrade [y/N]? ") except EOFError: print("") raise SystemExit() if answer in ["y", "Y"]: print("") # new line after answer else: raise SystemExit() dwn_link = ["https://{0}.com/{1}/{2}/archive/" "v{3}/{4}-{5}.tar.gz".format(repository, _meta_.__author__, _meta_.__all__, __new_version__, _meta_.__all__, __new_version__)] if not os.path.exists(_meta_.build_path): os.makedirs(_meta_.build_path) Download(_meta_.build_path, dwn_link, repo="").start() os.chdir(_meta_.build_path) slpkg_tar_file = "slpkg" + "-" + __new_version__ + ".tar.gz" tar = tarfile.open(slpkg_tar_file) tar.extractall() tar.close() file_name = "{0}-{1}".format(_meta_.__all__, __new_version__) os.chdir(file_name) check_md5(pkg_checksum(slpkg_tar_file, _meta_.__all__), _meta_.build_path + slpkg_tar_file) subprocess.call("chmod +x {0}".format("install.sh"), shell=True) subprocess.call("sh install.sh", shell=True) else: print("\n{0}: There is no new version, already used the last !" "\n".format(_meta_.__all__)) raise SystemExit()
<SYSTEM_TASK:> Check if all packages is already installed <END_TASK> <USER_TASK:> Description: def if_all_installed(self): """Check if all packages is already installed """
count_inst = 0 for inst in (self.dep_install + self.install): if (os.path.isfile(self.meta.pkg_path + inst[:-4]) and "--download-only" not in self.flag): count_inst += 1 if (count_inst == len(self.dep_install + self.install) and "--reinstall" not in self.flag): raise SystemExit()
<SYSTEM_TASK:> Clear master packages if already exist in dependencies <END_TASK> <USER_TASK:> Description: def clear_masters(self): """Clear master packages if already exist in dependencies or if added to install two or more times """
packages = [] for mas in Utils().remove_dbs(self.packages): if mas not in self.dependencies: packages.append(mas) self.packages = packages
<SYSTEM_TASK:> Install or upgrade packages <END_TASK> <USER_TASK:> Description: def install_packages(self): """Install or upgrade packages """
installs, upgraded = [], [] for inst in (self.dep_install + self.install): package = (self.tmp_path + inst).split() pkg_ver = "{0}-{1}".format(split_package(inst)[0], split_package(inst)[1]) self.checksums(inst) if GetFromInstalled(split_package(inst)[0]).name(): print("[ {0}upgrading{1} ] --> {2}".format( self.meta.color["YELLOW"], self.meta.color["ENDC"], inst)) upgraded.append(pkg_ver) if "--reinstall" in self.flag: PackageManager(package).upgrade("--reinstall") else: PackageManager(package).upgrade("--install-new") else: print("[ {0}installing{1} ] --> {2}".format( self.meta.color["GREEN"], self.meta.color["ENDC"], inst)) installs.append(pkg_ver) PackageManager(package).upgrade("--install-new") return [installs, upgraded]
<SYSTEM_TASK:> Don't downgrade packages if repository version is lower than <END_TASK> <USER_TASK:> Description: def not_downgrade(self, package): """Don't downgrade packages if repository version is lower than installed"""
name = split_package(package)[0] rep_ver = split_package(package)[1] ins_ver = GetFromInstalled(name).version()[1:] if not ins_ver: ins_ver = "0" if LooseVersion(rep_ver) < LooseVersion(ins_ver): self.msg.template(78) print("| Package {0} don't downgrade, " "setting by user".format(name)) self.msg.template(78) return True
<SYSTEM_TASK:> Checksums before install <END_TASK> <USER_TASK:> Description: def checksums(self, install): """Checksums before install """
check_md5(pkg_checksum(install, self.repo), self.tmp_path + install)
<SYSTEM_TASK:> Fix store deps include in repository <END_TASK> <USER_TASK:> Description: def _fix_deps_repos(self, dependencies): """Fix store deps include in repository """
requires = [] for dep in dependencies: if dep in self.repo_pkg_names: requires.append(dep) return requires
<SYSTEM_TASK:> Store and return packages for install <END_TASK> <USER_TASK:> Description: def store(self, packages): """Store and return packages for install """
dwn, install, comp_sum, uncomp_sum = ([] for i in range(4)) # name = data[0] # location = data[1] # size = data[2] # unsize = data[3] for pkg in packages: for pk, loc, comp, uncomp in zip(self.data[0], self.data[1], self.data[2], self.data[3]): if (pk and pkg == split_package(pk)[0] and pk not in install and split_package(pk)[0] not in self.blacklist): dwn.append("{0}{1}/{2}".format(self.mirror, loc, pk)) install.append(pk) comp_sum.append(comp) uncomp_sum.append(uncomp) if not install: for pkg in packages: for pk, loc, comp, uncomp in zip(self.data[0], self.data[1], self.data[2], self.data[3]): name = split_package(pk)[0] if (pk and pkg in name and name not in self.blacklist): self.matching = True dwn.append("{0}{1}/{2}".format(self.mirror, loc, pk)) install.append(pk) comp_sum.append(comp) uncomp_sum.append(uncomp) dwn.reverse() install.reverse() comp_sum.reverse() uncomp_sum.reverse() if self.repo == "slack": dwn, install, comp_sum, uncomp_sum = self.patches(dwn, install, comp_sum, uncomp_sum) return [dwn, install, comp_sum, uncomp_sum]
<SYSTEM_TASK:> Load packages from slpkg library and from local <END_TASK> <USER_TASK:> Description: def library(repo): """Load packages from slpkg library and from local """
pkg_list, packages = [], "" if repo == "sbo": if (os.path.isfile( _meta_.lib_path + "{0}_repo/SLACKBUILDS.TXT".format(repo))): packages = Utils().read_file(_meta_.lib_path + "{0}_repo/" "SLACKBUILDS.TXT".format(repo)) else: if (os.path.isfile( _meta_.lib_path + "{0}_repo/PACKAGES.TXT".format(repo))): packages = Utils().read_file(_meta_.lib_path + "{0}_repo/" "PACKAGES.TXT".format(repo)) for line in packages.splitlines(): if repo == "sbo": if line.startswith("SLACKBUILD NAME: "): pkg_list.append(line[17:].strip()) elif "local" not in repo: if line.startswith("PACKAGE NAME: "): pkg_list.append(line[15:].strip()) if repo == "local": pkg_list = find_package("", _meta_.pkg_path) return pkg_list
<SYSTEM_TASK:> Grab sources from .info file and store filename <END_TASK> <USER_TASK:> Description: def info_file(self): """Grab sources from .info file and store filename """
sources = SBoGrep(self.prgnam).source().split() for source in sources: self.sbo_sources.append(source.split("/")[-1])
<SYSTEM_TASK:> Help and version info <END_TASK> <USER_TASK:> Description: def help_version(self): """Help and version info """
if (len(self.args) == 1 and self.args[0] in ["-h", "--help"] and self.args[1:] == []): options() elif (len(self.args) == 1 and self.args[0] in ["-v", "--version"] and self.args[1:] == []): prog_version() else: usage("")
<SYSTEM_TASK:> Recreate repositories package lists <END_TASK> <USER_TASK:> Description: def command_upgrade(self): """Recreate repositories package lists """
if len(self.args) == 1 and self.args[0] == "upgrade": Initialization(False).upgrade(only="") elif (len(self.args) == 2 and self.args[0] == "upgrade" and self.args[1].startswith("--only=")): repos = self.args[1].split("=")[-1].split(",") for rp in repos: if rp not in self.meta.repositories: repos.remove(rp) Initialization(False).upgrade(repos) else: usage("")
<SYSTEM_TASK:> Auto built tool <END_TASK> <USER_TASK:> Description: def auto_build(self): """Auto built tool """
options = [ "-a", "--autobuild" ] if len(self.args) >= 3 and self.args[0] in options: AutoBuild(self.args[1], self.args[2:], self.meta.path).run() else: usage("")
<SYSTEM_TASK:> List of packages by repository <END_TASK> <USER_TASK:> Description: def pkg_list(self): """List of packages by repository """
options = [ "-l", "--list" ] flag = ["--index", "--installed", "--name"] name = INDEX = installed = False for arg in self.args[2:]: if flag[0] == arg: INDEX = True if flag[1] in arg: installed = True if flag[2] == arg: name = True if arg not in flag: usage("") raise SystemExit() if (len(self.args) > 1 and len(self.args) <= 5 and self.args[0] in options): if self.args[1] in self.meta.repositories: PackageManager(binary=None).package_list(self.args[1], name, INDEX, installed) else: usage(self.args[1]) else: usage("")
<SYSTEM_TASK:> Check and upgrade packages by repository <END_TASK> <USER_TASK:> Description: def pkg_upgrade(self): """Check and upgrade packages by repository """
options = [ "-c", "--check" ] flags = [ "--upgrade", "--skip=", "--resolve-off", "--checklist", "--rebuild" ] flag, skip = self.__pkg_upgrade_flags(flags) if (len(self.args) == 3 and self.args[0] in options and self.args[2] == flags[0] and self.args[1] in self.meta.repositories): if self.args[1] not in ["slack", "sbo"]: BinaryInstall(pkg_upgrade(self.args[1], skip, flag), self.args[1], flag).start(is_upgrade=True) elif self.args[1] == "slack": if self.meta.only_installed in ["on", "ON"]: BinaryInstall(pkg_upgrade("slack", skip, flag), "slack", flag).start(is_upgrade=True) else: Patches(skip, flag).start() elif self.args[1] == "sbo": SBoInstall(sbo_upgrade(skip, flag), flag).start(is_upgrade=True) else: usage(self.args[1]) elif len(self.args) == 2 and self.args[0] in options: if self.args[1] == "ALL": Updates(repo="").ALL() else: Updates(self.args[1]).run() elif (len(self.args) >= 2 and self.args[0] in options and self.args[1] not in self.meta.repositories): usage(self.args[1]) else: usage("")
<SYSTEM_TASK:> Install packages by repository <END_TASK> <USER_TASK:> Description: def pkg_install(self): """Install packages by repository """
flag = [] options = [ "-s", "--sync" ] additional_options = [ "--resolve-off", "--download-only", "--directory-prefix=", "--case-ins", "--rebuild", "--reinstall", "--patches" ] for arg in self.args: if arg.startswith(additional_options[2]): flag.append(arg) arg = "" if arg in additional_options: flag.append(arg) # clean from flags for ar in flag: if ar in self.args: self.args.remove(ar) if len(self.args) >= 3 and self.args[0] in options: if (self.args[1] in self.meta.repositories and self.args[1] not in ["sbo"]): BinaryInstall(self.args[2:], self.args[1], flag).start( is_upgrade=False) elif (self.args[1] == "sbo" and self.args[1] in self.meta.repositories): SBoInstall(self.args[2:], flag).start(is_upgrade=False) else: usage(self.args[1]) else: usage("")
<SYSTEM_TASK:> Find installed packages <END_TASK> <USER_TASK:> Description: def bin_find(self): """Find installed packages """
flag = [] options = [ "-f", "--find" ] additional_options = ["--case-ins"] for arg in self.args: if arg in additional_options: flag.append(arg) self.args.remove(arg) packages = self.args[1:] if len(self.args) > 1 and self.args[0] in options: PackageManager(packages).find(flag) else: usage("")
<SYSTEM_TASK:> Find packages from all enabled repositories <END_TASK> <USER_TASK:> Description: def pkg_find(self): """Find packages from all enabled repositories """
flag = [] options = [ "-F", "--FIND" ] additional_options = ["--case-ins"] for arg in self.args: if arg in additional_options: flag.append(arg) self.args.remove(arg) packages = self.args[1:] if len(self.args) > 1 and self.args[0] in options: FindFromRepos().find(packages, flag) else: usage("")
<SYSTEM_TASK:> Check for already Slackware binary packages exist <END_TASK> <USER_TASK:> Description: def auto_detect(self, args): """Check for already Slackware binary packages exist """
suffixes = [ ".tgz", ".txz", ".tbz", ".tlz" ] if (not args[0].startswith("-") and args[0] not in self.commands and args[0].endswith(tuple(suffixes))): packages, not_found = [], [] for pkg in args: if pkg.endswith(tuple(suffixes)): if os.path.isfile(pkg): packages.append(pkg) else: not_found.append(pkg) if packages: Auto(packages).select() if not_found: for ntf in not_found: self.msg.pkg_not_found("", ntf, "Not installed", "") raise SystemExit()
<SYSTEM_TASK:> Check all installed packages and create <END_TASK> <USER_TASK:> Description: def data(self): """Check all installed packages and create dictionary database """
for pkg in self.installed: if os.path.isfile(self.meta.pkg_path + pkg): name = split_package(pkg)[0] for log in self.logs: deps = Utils().read_file(self.dep_path + log) for dep in deps.splitlines(): if name == dep: if name not in self.dmap.keys(): self.dmap[name] = [log] if not self.count_pkg: self.count_pkg = 1 else: self.dmap[name] += [log] self.count_packages()
<SYSTEM_TASK:> Count dependencies and packages <END_TASK> <USER_TASK:> Description: def count_packages(self): """Count dependencies and packages """
packages = [] for pkg in self.dmap.values(): packages += pkg self.count_dep += 1 self.count_pkg = len(set(packages))
<SYSTEM_TASK:> Summary by packages and dependencies <END_TASK> <USER_TASK:> Description: def summary(self): """Summary by packages and dependencies """
print("\nStatus summary") print("=" * 79) print("{0}found {1} dependencies in {2} packages.{3}\n".format( self.grey, self.count_dep, self.count_pkg, self.endc))
<SYSTEM_TASK:> Start to find packages and print <END_TASK> <USER_TASK:> Description: def find(self, pkg, flag): """Start to find packages and print """
print("\nPackages with name matching [ {0}{1}{2} ]\n".format( self.cyan, ", ".join(pkg), self.endc)) Msg().template(78) print("| {0} {1}{2}{3}".format("Repository", "Package", " " * 54, "Size")) Msg().template(78) for repo in _meta_.repositories: PACKAGES_TXT = PackageManager(pkg).list_lib(repo) packages, sizes = PackageManager(pkg).list_greps(repo, PACKAGES_TXT) for find, size in zip(packages, sizes): for p in pkg: if "--case-ins" in flag: self.p_cache = p.lower() self.find_cache = find.lower() else: self.p_cache = p self.find_cache = find if self.p_cache in self.find_cache: if self.cache != repo: self.count_repo += 1 self.cache = repo self.count_pkg += 1 ver = self.sbo_version(repo, find) print(" {0}{1}{2}{3}{4} {5}{6:>11}".format( self.cyan, repo, self.endc, " " * (12 - len(repo)), find + ver, " " * (53 - len(find + ver)), size)) print("\nFound summary") print("=" * 79) print("{0}Total found {1} packages in {2} repositories." "{3}\n".format(self.grey, self.count_pkg, self.count_repo, self.endc))
<SYSTEM_TASK:> Write custom repository name and url in a file <END_TASK> <USER_TASK:> Description: def add(self, repo, url): """Write custom repository name and url in a file """
repo_name = [] if not url.endswith("/"): url = url + "/" for line in self.custom_repositories_list.splitlines(): line = line.lstrip() if line and not line.startswith("#"): repo_name.append(line.split()[0]) if (repo in self.meta.repositories or repo in repo_name or repo in self.meta.default_repositories): print("\nRepository name '{0}' exist, select different name.\n" "View all repositories with command 'slpkg " "repo-list'.\n".format(repo)) raise SystemExit() elif len(repo) > 6: print("\nslpkg: Error: Maximum repository name length must be " "six (6) characters\n") raise SystemExit() with open(self.custom_repo_file, "a") as repos: new_line = " {0}{1}{2}\n".format(repo, " " * (10 - len(repo)), url) repos.write(new_line) repos.close() print("\nRepository '{0}' successfully added\n".format(repo)) raise SystemExit()
<SYSTEM_TASK:> Return dictionary with default repo name and url <END_TASK> <USER_TASK:> Description: def default_repository(self): """Return dictionary with default repo name and url """
default_dict_repo = {} for line in self.default_repositories_list.splitlines(): line = line.lstrip() if not line.startswith("#"): if line.split()[0] in self.DEFAULT_REPOS_NAMES: default_dict_repo[line.split()[0]] = line.split()[1] else: print("\nslpkg: Error: Repository name '{0}' is not " "default.\n Please check file: " "/etc/slpkg/default-repositories\n".format( line.split()[0])) raise SystemExit() return default_dict_repo
<SYSTEM_TASK:> View SlackBuild package, read or install them <END_TASK> <USER_TASK:> Description: def view(self): """View SlackBuild package, read or install them from slackbuilds.org """
if self.sbo_url and self.name not in self.blacklist: self.prgnam = ("{0}-{1}".format(self.name, self.sbo_version)) self.view_sbo() while True: self.read_choice() choice = { "r": self.choice_README, "R": self.choice_README, "s": self.choice_SlackBuild, "S": self.choice_SlackBuild, "f": self.choice_info, "F": self.choice_info, "o": self.choice_doinst, "O": self.choice_doinst, "d": self.choice_download, "D": self.choice_download, "download": self.choice_download, "b": self.choice_build, "B": self.choice_build, "build": self.choice_build, "i": self.choice_install, "I": self.choice_install, "install": self.choice_install, "c": self.choice_clear_screen, "C": self.choice_clear_screen, "clear": self.choice_clear_screen, "q": self.choice_quit, "quit": self.choice_quit, "Q": self.choice_quit } try: choice[self.choice]() except KeyError: pass else: self.msg.pkg_not_found("\n", self.name, "Can't view", "\n") raise SystemExit(1)
<SYSTEM_TASK:> Download, build and install package <END_TASK> <USER_TASK:> Description: def choice_install(self): """Download, build and install package """
pkg_security([self.name]) if not find_package(self.prgnam, self.meta.pkg_path): self.build() self.install() delete(self.build_folder) raise SystemExit() else: self.msg.template(78) self.msg.pkg_found(self.prgnam) self.msg.template(78) raise SystemExit()
<SYSTEM_TASK:> Check if package supported by arch <END_TASK> <USER_TASK:> Description: def error_uns(self): """Check if package supported by arch before proceed to install """
self.FAULT = "" UNST = ["UNSUPPORTED", "UNTESTED"] if "".join(self.source_dwn) in UNST: self.FAULT = "".join(self.source_dwn)
<SYSTEM_TASK:> Only build and create Slackware package <END_TASK> <USER_TASK:> Description: def build(self): """Only build and create Slackware package """
pkg_security([self.name]) self.error_uns() if self.FAULT: print("") self.msg.template(78) print("| Package {0} {1} {2} {3}".format(self.prgnam, self.red, self.FAULT, self.endc)) self.msg.template(78) else: sources = [] if not os.path.exists(self.meta.build_path): os.makedirs(self.meta.build_path) if not os.path.exists(self._SOURCES): os.makedirs(self._SOURCES) os.chdir(self.meta.build_path) Download(self.meta.build_path, self.sbo_dwn.split(), repo="sbo").start() Download(self._SOURCES, self.source_dwn, repo="sbo").start() script = self.sbo_dwn.split("/")[-1] for src in self.source_dwn: sources.append(src.split("/")[-1]) BuildPackage(script, sources, self.meta.build_path, auto=False).build() slack_package(self.prgnam)
<SYSTEM_TASK:> Add packages in queue if not exist <END_TASK> <USER_TASK:> Description: def add(self, pkgs): """Add packages in queue if not exist """
queue_list = self.packages() pkgs = list(OrderedDict.fromkeys(pkgs)) print("\nAdd packages in the queue:\n") with open(self.queue_list, "a") as queue: for pkg in pkgs: find = sbo_search_pkg(pkg) if pkg not in queue_list and find is not None: print("{0}{1}{2}".format(self.meta.color["GREEN"], pkg, self.meta.color["ENDC"])) queue.write(pkg + "\n") self.quit = True else: print("{0}{1}{2}".format(self.meta.color["RED"], pkg, self.meta.color["ENDC"])) self.quit = True queue.close() if self.quit: print("")
<SYSTEM_TASK:> Remove packages from queue <END_TASK> <USER_TASK:> Description: def remove(self, pkgs): """Remove packages from queue """
print("\nRemove packages from the queue:\n") with open(self.queue_list, "w") as queue: for line in self.queued.splitlines(): if line not in pkgs: queue.write(line + "\n") else: print("{0}{1}{2}".format(self.meta.color["RED"], line, self.meta.color["ENDC"])) self.quit = True queue.close() if self.quit: print("")
<SYSTEM_TASK:> Build packages from queue <END_TASK> <USER_TASK:> Description: def build(self): """Build packages from queue """
packages = self.packages() if packages: for pkg in packages: if not os.path.exists(self.meta.build_path): os.mkdir(self.meta.build_path) if not os.path.exists(self._SOURCES): os.mkdir(self._SOURCES) sbo_url = sbo_search_pkg(pkg) sbo_dwn = SBoLink(sbo_url).tar_gz() source_dwn = SBoGrep(pkg).source().split() sources = [] os.chdir(self.meta.build_path) script = sbo_dwn.split("/")[-1] Download(self.meta.build_path, sbo_dwn.split(), repo="sbo").start() for src in source_dwn: Download(self._SOURCES, src.split(), repo="sbo").start() sources.append(src.split("/")[-1]) BuildPackage(script, sources, self.meta.build_path, auto=False).build() else: print("\nPackages not found in the queue for building\n") raise SystemExit(1)
<SYSTEM_TASK:> Split package in name, version <END_TASK> <USER_TASK:> Description: def split_package(package): """ Split package in name, version arch and build tag. """
name = ver = arch = build = [] split = package.split("-") if len(split) > 2: build = split[-1] build_a, build_b = "", "" build_a = build[:1] if build[1:2].isdigit(): build_b = build[1:2] build = build_a + build_b arch = split[-2] ver = split[-3] name = "-".join(split[:-3]) return [name, ver, arch, build]
<SYSTEM_TASK:> Grab all packages name <END_TASK> <USER_TASK:> Description: def names(self): """Grab all packages name """
pkg_names = [] for line in self.SLACKBUILDS_TXT.splitlines(): if line.startswith(self.line_name): pkg_names.append(line[17:].strip()) return pkg_names
<SYSTEM_TASK:> Grab package requirements <END_TASK> <USER_TASK:> Description: def requires(self): """Grab package requirements """
for line in self.SLACKBUILDS_TXT.splitlines(): if line.startswith(self.line_name): sbo_name = line[17:].strip() if line.startswith(self.line_req): if sbo_name == self.name: return line[21:].strip().split()
<SYSTEM_TASK:> Check if repository is local <END_TASK> <USER_TASK:> Description: def check_for_local_repos(repo): """Check if repository is local """
repos_dict = Repo().default_repository() if repo in repos_dict: repo_url = repos_dict[repo] if repo_url.startswith("file:///"): return True
<SYSTEM_TASK:> Creating slackers local library <END_TASK> <USER_TASK:> Description: def conrad(self): """Creating slackers local library """
repo = self.def_repos_dict["conrad"] log = self.log_path + "conrad/" lib = self.lib_path + "conrad_repo/" repo_name = log[:-1].split("/")[-1] lib_file = "PACKAGES.TXT" # lst_file = "" md5_file = "CHECKSUMS.md5" log_file = "ChangeLog.txt" if not os.path.exists(log): os.mkdir(log) if not os.path.exists(lib): os.mkdir(lib) PACKAGES_TXT = "{0}{1}".format(repo, lib_file) FILELIST_TXT = "" CHECKSUMS_MD5 = "{0}{1}".format(repo, md5_file) ChangeLog_txt = "{0}{1}".format(repo, log_file) if self.check: return self.checks_logs(log, ChangeLog_txt) self.down(lib, PACKAGES_TXT, repo_name) self.down(lib, CHECKSUMS_MD5, repo_name) self.down(log, ChangeLog_txt, repo_name) self.remote(log, ChangeLog_txt, lib, PACKAGES_TXT, CHECKSUMS_MD5, FILELIST_TXT, repo_name)
<SYSTEM_TASK:> Remove and recreate files <END_TASK> <USER_TASK:> Description: def remote(self, *args): """Remove and recreate files """
log_path = args[0] ChangeLog_txt = args[1] lib_path = args[2] PACKAGES_TXT = args[3] CHECKSUMS_MD5 = args[4] FILELIST_TXT = args[5] repo = args[6] if self.checks_logs(log_path, ChangeLog_txt): # remove old files self.file_remove(log_path, ChangeLog_txt.split("/")[-1]) self.file_remove(lib_path, PACKAGES_TXT.split("/")[-1]) self.file_remove(lib_path, CHECKSUMS_MD5.split("/")[-1]) self.file_remove(lib_path, FILELIST_TXT.split("/")[-1]) if repo == "slack": dirs = ["core/", "extra/", "pasture/"] for d in dirs: self.file_remove(lib_path + d, "PACKAGES.TXT") self.file_remove(lib_path + d, "CHECKSUMS.md5") self.down(lib_path + "core/", PACKAGES_TXT, repo) self.down(lib_path + "core/", CHECKSUMS_MD5, repo) self.down(lib_path + "extra/", self.EXTRA, repo) self.down(lib_path + "extra/", self.EXT_CHECKSUMS, repo) if slack_ver() != "14.0": # no pasture/ folder for 14.0 version self.down(lib_path + "pasture/", self.PASTURE, repo) self.down(lib_path + "pasture/", self.PAS_CHECKSUMS, repo) # download new files if repo != "slack": self.down(lib_path, PACKAGES_TXT, repo) self.down(lib_path, CHECKSUMS_MD5, repo) self.down(lib_path, FILELIST_TXT, repo) self.down(log_path, ChangeLog_txt, repo)
<SYSTEM_TASK:> Check if filename exists and remove <END_TASK> <USER_TASK:> Description: def file_remove(self, path, filename): """Check if filename exists and remove """
if os.path.isfile(path + filename): os.remove(path + filename)
<SYSTEM_TASK:> Remove all package lists with changelog and checksums files <END_TASK> <USER_TASK:> Description: def upgrade(self, only): """Remove all package lists with changelog and checksums files and create lists again"""
repositories = self.meta.repositories if only: repositories = only for repo in repositories: changelogs = "{0}{1}{2}".format(self.log_path, repo, "/ChangeLog.txt") if os.path.isfile(changelogs): os.remove(changelogs) if os.path.isdir(self.lib_path + "{0}_repo/".format(repo)): for f in (os.listdir(self.lib_path + "{0}_repo/".format( repo))): files = "{0}{1}_repo/{2}".format(self.lib_path, repo, f) if os.path.isfile(files): os.remove(files) elif os.path.isdir(files): shutil.rmtree(files) Update().repository(only)
<SYSTEM_TASK:> Delete build directory and all its contents. <END_TASK> <USER_TASK:> Description: def delete(build_folder): """Delete build directory and all its contents. """
if _meta_.del_build in ["on", "ON"] and os.path.exists(build_folder): shutil.rmtree(build_folder)
<SYSTEM_TASK:> Install new patches from official Slackware mirrors <END_TASK> <USER_TASK:> Description: def start(self): """ Install new patches from official Slackware mirrors """
self.store() self.msg.done() if self.upgrade_all: if "--checklist" in self.flag: self.dialog_checklist() print("\nThese packages need upgrading:\n") self.msg.template(78) print("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}".format( "| Package", " " * 17, "New Version", " " * 8, "Arch", " " * 4, "Build", " " * 2, "Repos", " " * 10, "Size")) self.msg.template(78) print("Upgrading:") self.views() unit, size = units(self.comp_sum, self.uncomp_sum) print("\nInstalling summary") print("=" * 79) print("{0}Total {1} {2} will be upgraded and {3} will be " "installed.".format(self.meta.color["GREY"], self.count_upg, self.msg.pkg(self.upgrade_all), self.count_added)) print("Need to get {0} {1} of archives.".format(size[0], unit[0])) print("After this process, {0} {1} of additional disk space " "will be used.{2}".format(size[1], unit[1], self.meta.color["ENDC"])) print("") if self.msg.answer() in ["y", "Y"]: Download(self.patch_path, self.dwn_links, repo="slack").start() self.upgrade_all = self.utils.check_downloaded( self.patch_path, self.upgrade_all) self.upgrade() self.kernel() if self.meta.slackpkg_log in ["on", "ON"]: self.slackpkg_update() self.msg.reference(self.installed, self.upgraded) delete_package(self.patch_path, self.upgrade_all) self.update_lists() else: slack_arch = "" if self.meta.arch == "x86_64": slack_arch = "64" print("\nSlackware{0} '{1}' v{2} distribution is up to " "date\n".format(slack_arch, self.version, slack_ver()))
<SYSTEM_TASK:> Store and return packages for upgrading <END_TASK> <USER_TASK:> Description: def store(self): """ Store and return packages for upgrading """
data = repo_data(self.PACKAGES_TXT, "slack", self.flag) black = BlackList().packages(pkgs=data[0], repo="slack") for name, loc, comp, uncomp in zip(data[0], data[1], data[2], data[3]): status(0.0003) repo_pkg_name = split_package(name)[0] if (not os.path.isfile(self.meta.pkg_path + name[:-4]) and repo_pkg_name not in black and repo_pkg_name not in self.skip): self.dwn_links.append("{0}{1}/{2}".format(mirrors("", ""), loc, name)) self.comp_sum.append(comp) self.uncomp_sum.append(uncomp) self.upgrade_all.append(name) self.count_upg += 1 if not find_package(repo_pkg_name + self.meta.sp, self.meta.pkg_path): self.count_added += 1 self.count_upg -= 1 return self.count_upg
<SYSTEM_TASK:> Check if kernel upgraded if true <END_TASK> <USER_TASK:> Description: def kernel(self): """ Check if kernel upgraded if true then reinstall "lilo" """
for core in self.upgrade_all: if "kernel" in core: if self.meta.default_answer in ["y", "Y"]: answer = self.meta.default_answer else: print("") self.msg.template(78) print("| {0}*** HIGHLY recommended reinstall 'LILO' " "***{1}".format(self.meta.color["RED"], self.meta.color["ENDC"])) self.msg.template(78) try: answer = raw_input("\nThe kernel has been upgraded, " "reinstall `LILO` [y/N]? ") except EOFError: print("") raise SystemExit() if answer in ["y", "Y"]: subprocess.call("lilo", shell=True) break
<SYSTEM_TASK:> This replace slackpkg ChangeLog.txt file with new <END_TASK> <USER_TASK:> Description: def slackpkg_update(self): """This replace slackpkg ChangeLog.txt file with new from Slackware official mirrors after update distribution. """
NEW_ChangeLog_txt = URL(mirrors("ChangeLog.txt", "")).reading() if os.path.isfile(self.meta.slackpkg_lib_path + "ChangeLog.txt.old"): os.remove(self.meta.slackpkg_lib_path + "ChangeLog.txt.old") if os.path.isfile(self.meta.slackpkg_lib_path + "ChangeLog.txt"): shutil.copy2(self.meta.slackpkg_lib_path + "ChangeLog.txt", self.meta.slackpkg_lib_path + "ChangeLog.txt.old") os.remove(self.meta.slackpkg_lib_path + "ChangeLog.txt") with open(self.meta.slackpkg_lib_path + "ChangeLog.txt", "w") as log: log.write(NEW_ChangeLog_txt) log.close()
<SYSTEM_TASK:> Update packages list and ChangeLog.txt file after <END_TASK> <USER_TASK:> Description: def update_lists(self): """Update packages list and ChangeLog.txt file after upgrade distribution """
print("{0}Update the package lists ?{1}".format( self.meta.color["GREEN"], self.meta.color["ENDC"])) print("=" * 79) if self.msg.answer() in ["y", "Y"]: Update().repository(["slack"])
<SYSTEM_TASK:> write headers to log file <END_TASK> <USER_TASK:> Description: def log_head(path, log_file, log_time): """ write headers to log file """
with open(path + log_file, "w") as log: log.write("#" * 79 + "\n\n") log.write("File : " + log_file + "\n") log.write("Path : " + path + "\n") log.write("Date : " + time.strftime("%d/%m/%Y") + "\n") log.write("Time : " + log_time + "\n\n") log.write("#" * 79 + "\n\n") log.close()
<SYSTEM_TASK:> Calculate build time per package <END_TASK> <USER_TASK:> Description: def build_time(start_time): """ Calculate build time per package """
diff_time = round(time.time() - start_time, 2) if diff_time <= 59.99: sum_time = str(diff_time) + " Sec" elif diff_time > 59.99 and diff_time <= 3599.99: sum_time = round(diff_time / 60, 2) sum_time_list = re.findall(r"\d+", str(sum_time)) sum_time = ("{0} Min {1} Sec".format(sum_time_list[0], sum_time_list[1])) elif diff_time > 3599.99: sum_time = round(diff_time / 3600, 2) sum_time_list = re.findall(r"\d+", str(sum_time)) sum_time = ("{0} Hours {1} Min".format(sum_time_list[0], sum_time_list[1])) return sum_time
<SYSTEM_TASK:> Set variable MAKEFLAGS with the numbers of <END_TASK> <USER_TASK:> Description: def _makeflags(self): """Set variable MAKEFLAGS with the numbers of processors """
if self.meta.makeflags in ["on", "ON"]: cpus = multiprocessing.cpu_count() os.environ["MAKEFLAGS"] = "-j{0}".format(cpus)
<SYSTEM_TASK:> Delete slackbuild tar.gz file after untar <END_TASK> <USER_TASK:> Description: def _delete_sbo_tar_gz(self): """Delete slackbuild tar.gz file after untar """
if not self.auto and os.path.isfile(self.meta.build_path + self.script): os.remove(self.meta.build_path + self.script)