Kaydet (Commit) ae3d2917 authored tarafından Suleyman Poyraz's avatar Suleyman Poyraz

Merge remote-tracking branch 'origin/master'

# -*- coding: utf-8 -*-
#
# documentation build configuration file, created by
# sphinx-quickstart on Wen Feb 7 18:41:23 2018
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed
# automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys
import os
# pip install sphinx_rtd_theme
# import sphinx_rtd_theme
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
VERSION = '1.0'
AUTHOR = 'Zaryob'
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings.
# They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
# Later on, add 'sphinx.ext.viewcode' to the list if you want to have
# colorized code generated too for references.
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'Inary Documentation'
copyright = "2016-2017 Zaryob"
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = VERSION
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
# unused_docs = []
# List of directories, relative to source directories, that shouldn't be
# searched for source files.
# exclude_dirs = []
# A list of glob-style patterns that should be excluded when looking
# for source files.
exclude_patterns = ['modules']
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
highlight_language = 'YAML+Jinja'
# Substitutions, variables, entities, & shortcuts for text which do not need to link to anything.
# For titles which should be a link, use the intersphinx anchors set at the index, chapter, and
# section levels, such as qi_start_:
rst_epilog = """
"""
# Options for HTML output
# -----------------------
html_theme_path = ['../_themes']
html_theme = 'highlight'
html_short_title = 'Inary Documentation'
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
# html_style = 'solar.css'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = 'Inary Documentation'
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (within the static path) to place at the top of
# the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'favicon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['.static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_use_modindex = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
html_copy_source = False
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Poseidodoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
# latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
# latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class
# [howto/manual]).
latex_documents = [
('index', 'ansible.tex', 'Ansible 2.2 Documentation', AUTHOR, 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# Additional stuff for the LaTeX preamble.
# latex_preamble = ''
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_use_modindex = True
autoclass_content = 'both'
intersphinx_mapping = {'python3': ('https://docs.python.org/3/', (None, '../python3-3.6.2.inv')),
'jinja2': ('http://jinja.pocoo.org/docs/', (None, '../jinja2-2.9.7.inv'))}
......@@ -61,10 +61,13 @@ def curPYTHON():
def curPERL():
""" returns currently used perl's version"""
<<<<<<< HEAD
# for i in os.listdir("/usr/bin"):
# if i.startswith("perl"):
# if i.split("perl")[1]
=======
>>>>>>> master
return os.path.realpath('/usr/bin/perl').split('perl')[1]
......
......@@ -12,6 +12,10 @@
# Please read the COPYING file.
"""supports globs in sourceFile arguments"""
<<<<<<< HEAD
=======
>>>>>>> master
import filecmp
import fileinput
......@@ -89,8 +93,12 @@ def readable_insinto(destinationDirectory, *sourceFiles):
for source in sourceFileGlob:
system('install -m 0644 "{0}" {1}'.format(source, destinationDirectory))
<<<<<<< HEAD
def lib_insinto(sourceFile, destinationDirectory, permission=644):
=======
def lib_insinto(sourceFile, destinationDirectory, permission = 644):
>>>>>>> master
"""inserts a library fileinto destinationDirectory with given permission"""
if not sourceFile or not destinationDirectory:
......@@ -106,13 +114,21 @@ def lib_insinto(sourceFile, destinationDirectory, permission=644):
# inarytools funtions
<<<<<<< HEAD
def dobin(sourceFile, destinationDirectory='/usr/bin'):
=======
def dobin(sourceFile, destinationDirectory = '/usr/bin'):
>>>>>>> master
"""insert a executable file into /bin or /usr/bin"""
''' example call: inarytools.dobin("bin/xloadimage", "/bin", "xload") '''
executable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile)
<<<<<<< HEAD
def dopixmaps(sourceFile, destinationDirectory='/usr/share/pixmaps'):
=======
def dopixmaps(sourceFile, destinationDirectory = '/usr/share/pixmaps'):
>>>>>>> master
"""insert a data file into /usr/share/pixmaps"""
''' example call: inarytools.dopixmaps("/usr/share/pixmaps/firefox", "firefox") '''
readable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile)
......@@ -166,8 +182,12 @@ def doinfo(*sourceFiles):
"""inserts the into files in the list of files into /usr/share/info"""
readable_insinto(join_path(get.installDIR(), get.infoDIR()), *sourceFiles)
<<<<<<< HEAD
def dolib(sourceFile, destinationDirectory='/usr/lib', mode=755):
=======
def dolib(sourceFile, destinationDirectory = '/usr/lib', mode=755):
>>>>>>> master
"""insert the library into /usr/lib"""
'''example call: inarytools.dolib("libz.a")'''
'''example call: inarytools.dolib("libz.so")'''
......@@ -209,8 +229,12 @@ def doman(*sourceFiles):
else:
uncompress(compressed, targetDir=manPDIR)
<<<<<<< HEAD
def domo(sourceFile, locale, destinationFile, localeDirPrefix='/usr/share/locale'):
=======
def domo(sourceFile, locale, destinationFile, localeDirPrefix = '/usr/share/locale'):
>>>>>>> master
"""inserts the mo files in the list of files into /usr/share/locale/LOCALE/LC_MESSAGES"""
'''example call: inarytools.domo("po/tr.po", "tr", "pam_login.mo")'''
......@@ -219,8 +243,12 @@ def domo(sourceFile, locale, destinationFile, localeDirPrefix='/usr/share/locale
makedirs('{0}{1}/{2}/LC_MESSAGES/'.format(get.installDIR(), localeDirPrefix, locale))
move('messages.mo', '{0}{1}/{2}/LC_MESSAGES/{3}'.format(get.installDIR(), localeDirPrefix, locale, destinationFile))
<<<<<<< HEAD
def domove(sourceFile, destination, destinationFile=''):
=======
def domove(sourceFile, destination, destinationFile = ''):
>>>>>>> master
"""moves sourceFile/Directory into destinationFile/Directory"""
''' example call: inarytools.domove("/usr/bin/bash", "/bin/bash")'''
......@@ -251,8 +279,12 @@ def rename(sourceFile, destinationFile):
except OSError as e:
error(_('ActionsAPI [rename]: {0}: {1}').format(e, sourceFile))
<<<<<<< HEAD
def dosed(sources, findPattern, replacePattern='', filePattern='', deleteLine=False, level=-1):
=======
def dosed(sources, findPattern, replacePattern = '', filePattern = '', deleteLine = False, level = -1):
>>>>>>> master
"""replaces patterns in sources"""
''' example call: inarytools.dosed("/etc/passwd", "caglar", "cem")'''
......@@ -309,8 +341,12 @@ def dosed(sources, findPattern, replacePattern='', filePattern='', deleteLine=Fa
else:
raise FileError(_('File does not exist or permission denied: {}').format(sourceFile))
<<<<<<< HEAD
def dosbin(sourceFile, destinationDirectory='/usr/sbin'):
=======
def dosbin(sourceFile, destinationDirectory = '/usr/sbin'):
>>>>>>> master
"""insert a executable file into /sbin or /usr/sbin"""
''' example call: inarytools.dobin("bin/xloadimage", "/sbin") '''
......@@ -328,8 +364,12 @@ def dosym(sourceFile, destinationFile):
except OSError:
error(_('ActionsAPI [dosym]: File already exists: {}').format(destinationFile))
<<<<<<< HEAD
def insinto(destinationDirectory, sourceFile, destinationFile='', sym=True):
=======
def insinto(destinationDirectory, sourceFile, destinationFile = '', sym = True):
>>>>>>> master
"""insert a sourceFile into destinationDirectory as a destinationFile with same uid/guid/permissions"""
makedirs(join_path(get.installDIR(), destinationDirectory))
......@@ -348,6 +388,10 @@ def insinto(destinationDirectory, sourceFile, destinationFile='', sym=True):
def newdoc(sourceFile, destinationFile):
"""inserts a sourceFile into /usr/share/doc/PACKAGE/ directory as a destinationFile"""
<<<<<<< HEAD
=======
destinationDirectory = '' #490
>>>>>>> master
destinationDirectory = os.path.dirname(destinationFile)
destinationFile = os.path.basename(destinationFile)
# Use copy instead of move or let build-install scream like file not found!
......
......@@ -41,8 +41,12 @@ docdir = "/{0}/{1}".format(get.docDIR(), basename)
htmldir = "{}/html".format(docdir)
wallpapersdir = "{}/share/wallpapers".format(prefix)
<<<<<<< HEAD
def configure(parameters='', installPrefix=prefix, sourceDir='..'):
=======
def configure(parameters = '', installPrefix = prefix, sourceDir = '..'):
>>>>>>> master
""" parameters -DLIB_INSTALL_DIR="hede" -DSOMETHING_USEFUL=1"""
shelltools.makedirs("build")
......
......@@ -52,8 +52,12 @@ class InstallError(inary.actionsapi.Error):
self.value = value
ctx.ui.error(value)
<<<<<<< HEAD
def configure(parameters=''):
=======
def configure(parameters = ''):
>>>>>>> master
"""configure source with given parameters."""
export('PERL_MM_USE_DEFAULT', '1')
if can_access_file('Build.PL'):
......@@ -64,8 +68,12 @@ def configure(parameters=''):
get.installDIR())):
raise ConfigureError(_('Configure failed.'))
<<<<<<< HEAD
def make(parameters=''):
=======
def make(parameters = ''):
>>>>>>> master
"""make source with given parameters."""
if can_access_file('Makefile'):
if system('make {}'.format(parameters)):
......@@ -74,8 +82,12 @@ def make(parameters=''):
if system('perl{0} Build {1}'.format(get.curPERL(), parameters)):
raise MakeError(_('perl build failed.'))
<<<<<<< HEAD
def install(parameters='install'):
=======
def install(parameters = 'install'):
>>>>>>> master
"""install source with given parameters."""
if can_access_file('Makefile'):
if system('make {}'.format(parameters)):
......@@ -87,8 +99,12 @@ def install(parameters='install'):
removePacklist()
removePodfiles()
<<<<<<< HEAD
def removePacklist(path='usr/lib/perl5/'):
=======
def removePacklist(path = 'usr/lib/perl5/'):
>>>>>>> master
""" cleans .packlist file from perl packages """
full_path = '{0}/{1}'.format(get.installDIR(), path)
for root, dirs, files in os.walk(full_path):
......@@ -98,8 +114,12 @@ def removePacklist(path='usr/lib/perl5/'):
unlink('{0}/{1}'.format(root, packFile))
removeEmptydirs(root)
<<<<<<< HEAD
def removePodfiles(path='usr/lib/perl5/'):
=======
def removePodfiles(path = 'usr/lib/perl5/'):
>>>>>>> master
""" cleans *.pod files from perl packages """
full_path = '{0}/{1}'.format(get.installDIR(), path)
for root, dirs, files in os.walk(full_path):
......
......@@ -57,20 +57,32 @@ class RunTimeError(inary.actionsapi.Error):
self.value = value
ctx.ui.error(value)
<<<<<<< HEAD
def configure(parameters='', pyVer=''):
=======
def configure(parameters = '', pyVer = ''):
>>>>>>> master
"""does python setup.py configure"""
if system('python{0} setup.py configure {1}'.format(pyVer, parameters)):
raise ConfigureError(_('Configuration failed.'))
<<<<<<< HEAD
def compile(parameters='', pyVer=''):
=======
def compile(parameters = '', pyVer = ''):
>>>>>>> master
"""compile source with given parameters."""
if system('python{0} setup.py build {1}'.format(pyVer, parameters)):
raise CompileError(_('Make failed.'))
<<<<<<< HEAD
def install(parameters='', pyVer=''):
=======
def install(parameters = '', pyVer = ''):
>>>>>>> master
"""does python setup.py install"""
if system('python{0} setup.py install --root={1} --no-compile -O0 {2}'.format(pyVer, get.installDIR(), parameters)):
raise InstallError(_('Install failed.'))
......@@ -84,16 +96,26 @@ def install(parameters='', pyVer=''):
if not isEmpty(doc):
dodoc(doc)
<<<<<<< HEAD
def run(parameters='', pyVer=''):
=======
def run(parameters = '', pyVer = ''):
>>>>>>> master
"""executes parameters with python"""
if system('python{0} {1}'.format(pyVer, parameters)):
raise RunTimeError(_('Running {} failed.').format(parameters))
<<<<<<< HEAD
def fixCompiledPy(lookInto='/usr/lib/{}/'.format(get.curPYTHON())):
""" cleans *.py[co] from packages """
for root, dirs, files in os.walk('{0}/{1}'.format(get.installDIR(), lookInto)):
=======
def fixCompiledPy(lookInto = '/usr/lib/{}/'.format(get.curPYTHON())):
""" cleans *.py[co] from packages """
for root, dirs, files in os.walk('{0}/{1}'.format(get.installDIR(),lookInto)):
>>>>>>> master
for compiledFile in files:
if compiledFile.endswith('.pyc') or compiledFile.endswith('.pyo'):
if can_access_file('{0}/{1}'.format(root, compiledFile)):
......
......@@ -102,8 +102,12 @@ def auto_dodoc():
def install(parameters=''):
"""does ruby setup.rb install"""
<<<<<<< HEAD
if system(
'ruby -w setup.rb --prefix=/{0.defaultprefixDIR()} --destdir={0.installDIR()} {1}'.format(get, parameters)):
=======
if system('ruby -w setup.rb --prefix=/{0.defaultprefixDIR()} --destdir={0.installDIR()} {1}'.format(get, parameters)):
>>>>>>> master
raise InstallError(_('Install failed.'))
auto_dodoc()
......
......@@ -61,8 +61,12 @@ def echo(destionationFile, content):
except IOError:
error(_('ActionsAPI [echo]: Can\'t append to file {}.').format(destionationFile))
<<<<<<< HEAD
def chmod(filePath, mode=0o755):
=======
def chmod(filePath, mode = 0o755):
>>>>>>> master
"""change the mode of filePath to the mode"""
filePathGlob = glob.glob(filePath)
if len(filePathGlob) == 0:
......@@ -77,8 +81,12 @@ def chmod(filePath, mode=0o755):
else:
ctx.ui.error(_('ActionsAPI [chmod]: File {} doesn\'t exists.').format(fileName))
<<<<<<< HEAD
def chown(filePath, uid='root', gid='root'):
=======
def chown(filePath, uid = 'root', gid = 'root'):
>>>>>>> master
"""change the owner and group id of filePath to uid and gid"""
if can_access_file(filePath):
try:
......@@ -150,8 +158,13 @@ def move(source, destination):
# FIXME: instead of passing a sym parameter, split copy and copytree into 4 different function
<<<<<<< HEAD
def copy(source, destination, sym=True):
"""recursively copy a "source" file or directory to "destination\" """
=======
def copy(source, destination, sym = True):
"""recursively copy a "source" file or directory to "destination\""""
>>>>>>> master
sourceGlob = glob.glob(source)
if len(sourceGlob) == 0:
error(_("ActionsAPI [copy]: No file matched pattern \"{}\".").format(source))
......@@ -179,8 +192,12 @@ def copy(source, destination, sym=True):
else:
error(_('ActionsAPI [copy]: File {} does not exist.').format(filePath))
<<<<<<< HEAD
def copytree(source, destination, sym=True):
=======
def copytree(source, destination, sym = True):
>>>>>>> master
"""recursively copy an entire directory tree rooted at source"""
if isDirectory(source):
if os.path.exists(destination):
......@@ -215,8 +232,12 @@ def touch(filePath):
except IOError:
error(_('ActionsAPI [touch]: Permission denied: {}').format(filePath))
<<<<<<< HEAD
def cd(directoryName=''):
=======
def cd(directoryName = ''):
>>>>>>> master
"""change directory"""
current = os.getcwd()
if directoryName:
......
......@@ -51,8 +51,12 @@ class RunTimeError(inary.actionsapi.Error):
self.value = value
ctx.ui.error(value)
<<<<<<< HEAD
def compile(parameters=''):
=======
def compile(parameters = ''):
>>>>>>> master
"""compiling texlive packages"""
# Move sources according to tplobj files
......@@ -65,8 +69,12 @@ def compile(parameters=''):
if buildFormatFiles():
raise CompileError(_('Building format files failed'))
<<<<<<< HEAD
def install(parameters=''):
=======
def install(parameters = ''):
>>>>>>> master
"""Installing texlive packages"""
# Create symlinks from format to engines
......@@ -154,7 +162,11 @@ def installConfigFiles():
def handleConfigFiles():
"""Handling config files"""
<<<<<<< HEAD
for root, dirs, files in os.walk("{}/usr/share/texmf".format(get.installDIR())):
=======
for root, dirs,files in os.walk("{}/usr/share/texmf".format(get.installDIR())):
>>>>>>> master
if not ("config" in root or "doc" in root):
for configFile in files:
if configFile.endswith(("cfg", "cnf")):
......
......@@ -48,7 +48,10 @@ def exportFlags():
class Env(object):
"""General environment variables used in actions API"""
<<<<<<< HEAD
=======
>>>>>>> master
def __init__(self):
exportFlags()
......
......@@ -70,5 +70,11 @@ class Dependency(relation.Relation, metaclass=autoxml.autoxml):
return self.satisfies_relation(pkg.version, pkg.release)
# Added for AnyDependency, single Dependency always returns False
<<<<<<< HEAD
def satisfied_by_any_installed_other_than(self):
pass
=======
@staticmethod
def satisfied_by_any_installed_other_than(package):
return False
>>>>>>> master
......@@ -453,6 +453,10 @@ class ArchiveTar(ArchiveBase):
# Try to extract again.
self.tar.extract(tarinfo)
<<<<<<< HEAD
=======
except OSError as e:
>>>>>>> master
# Handle the case where new path is file, but old path is directory
# due to not possible touch file c in /a/b if directory /a/b/c exists.
if not e.errno == errno.EISDIR:
......
......@@ -53,8 +53,13 @@ class NotfoundError(inary.errors.Error):
class AtomicOperation(object):
<<<<<<< HEAD
def __init__(self, ignore_dep=None):
# self.package = package
=======
def __init__(self, ignore_dep = None):
#self.package = package
>>>>>>> master
if ignore_dep is None:
self.ignore_dep = ctx.config.get_option('ignore_dependency')
else:
......@@ -74,6 +79,7 @@ opttostr = {INSTALL: "install", REMOVE: "remove", REINSTALL: "reinstall", UPGRAD
class Install(AtomicOperation):
"""Install class, provides install routines for inary packages"""
<<<<<<< HEAD
def __init__(self, package_fname, ignore_dep=None, ignore_file_conflicts=None,installdb=None,filesdb=None):
if installdb == None:
......@@ -103,6 +109,8 @@ class Install(AtomicOperation):
self.operation = INSTALL
self.store_old_paths = None
=======
>>>>>>> master
@staticmethod
def from_name(name,ignore_dep=None,packagedb=None,installdb=None,filesdb=None):
......
......@@ -30,6 +30,7 @@ __trans = gettext.translation('inary', fallback=True)
_ = __trans.gettext
class Error(inary.errors.Error):
pass
......@@ -63,7 +64,11 @@ class CLI(inary.ui.UI):
def output(self, msg, err=False, verbose=False):
if (verbose and self.show_verbose) or (not verbose):
<<<<<<< HEAD
if isinstance(msg, bytes):
=======
if type(msg) == type(bytes()):
>>>>>>> master
msg = msg.decode('utf-8')
if err:
sys.stderr.write(str(msg))
......@@ -150,7 +155,11 @@ class CLI(inary.ui.UI):
def choose(self, msg, opts):
msg = str(msg)
endmsg = '\n Select one:'
<<<<<<< HEAD
prompt = msg + util.colorize('[ %s ]' % (" / ".join(opts)), 'brightblue') + endmsg
=======
prompt = msg + inary.util.colorize('[ %s ]' % (" / ".join(opts)), 'brightblue') + endmsg
>>>>>>> master
while True:
s = input(prompt)
......@@ -171,7 +180,16 @@ class CLI(inary.ui.UI):
tty.tcflush(sys.stdin.fileno(), 0)
prompt = msg + util.colorize(" "+_('(yes'), 'green') + '/' + util.colorize(_('no)'), 'red')
s = input(prompt)
<<<<<<< HEAD
return yes_expr.search(s)
=======
if yes_expr.search(s):
return True
if no_expr.search(s):
return False
>>>>>>> master
def display_progress(self, **ka):
""" display progress of any operation """
......@@ -179,7 +197,17 @@ class CLI(inary.ui.UI):
return
elif ka['operation'] == "fetching":
<<<<<<< HEAD
totalsize = '%.1f %s' % util.human_readable_size(ka['total_size'])
=======
totalsize = '%.1f %s' % inary.util.human_readable_size(ka['total_size'])
out = '\r%-30.50s (%s)%3d%% %9.2f %s [%s]' % \
(ka['filename'], totalsize, ka['percent'],
ka['rate'], ka['symbol'], ka['eta'])
self.output(out)
else:
self.output("\r%s (%d%%)" % (ka['info'], ka['percent']))
>>>>>>> master
out = '%-30.50s(%s)' % (ka['filename'], totalsize)
out2= '%3d%% %9.2f%s [%s]' % (ka['percent'], ka['rate'],ka['symbol'], ka['eta'])
......@@ -190,7 +218,11 @@ class CLI(inary.ui.UI):
self.output("\r\033[2K"+colorize_percent(("%s" % ka['info']),ka['percent'],("(%d%%)" % ka['percent'])))
util.xterm_title("%s (%d%%)" % (ka['info'], ka['percent']))
<<<<<<< HEAD
def status(self, msg=None, push_screen=True):
=======
def status(self, msg=None):
>>>>>>> master
if msg:
msg = str(msg)
if push_screen:
......
......@@ -102,7 +102,10 @@ class Build(command.Command, metaclass=command.autocommand):
help=_("Do not constrain build process inside "
"the build folder"))
<<<<<<< HEAD
self.parser.add_option_group(group)
=======
>>>>>>> master
group = optparse.OptionGroup(self.parser, _("build steps"))
group.add_option("--fetch",
......@@ -151,6 +154,8 @@ class Build(command.Command, metaclass=command.autocommand):
help=_("Create INARY package"))
self.parser.add_option_group(group)
self.add_options(group)
self.parser.add_option_group(group)
def run(self):
if not self.options.quiet:
......
......@@ -49,6 +49,8 @@ Downloads the given inary packages to working directory
self.parser.add_option_group(group)
self.parser.add_option_group(group)
def run(self):
packages = inary.db.packagedb.PackageDB()
self.init(database=False, write=False)
......
......@@ -58,7 +58,11 @@ Usage: info <package1> <package2> ... <packagen>
group.add_option("-s", "--short", action="store_true",
default=False, help=_("Do not show details"))
group.add_option("--xml", action="store_true",
<<<<<<< HEAD
default=False, help=_("Output in xml format"))
=======
default=False, help=_("Output in xml format"))
>>>>>>> master
self.parser.add_option_group(group)
def run(self):
......
This diff is collapsed.
......@@ -36,7 +36,10 @@ class Singleton(type):
class _constant:
"""Constant members implementation"""
<<<<<<< HEAD
=======
>>>>>>> master
class ConstError(TypeError):
pass
......
......@@ -14,6 +14,10 @@
"""Files module provides access to files.xml. files.xml is generated
during the build process of a package and used in installation."""
<<<<<<< HEAD
=======
>>>>>>> master
import inary.sxml.autoxml as autoxml
......
......@@ -52,6 +52,7 @@ class Digraph(object):
l = []
for u in self.__v:
for v in self.__adj[u]:
<<<<<<< HEAD
l.append((u, v))
return l
......@@ -73,6 +74,29 @@ class Digraph(object):
self.__adj[u].add(v)
if edata is not None:
self.__edata[u][v] = edata
=======
l.append( (u,v) )
return l
def add_vertex(self, u, data = None):
"""add vertex u, optionally with data"""
assert not u in self.__v
self.__v.add(u)
self.__adj[u] = set()
if data:
self.__vdata[u] = data
self.__edata[u] = {}
def add_edge(self, u, v, edata = None, udata = None, vdata = None):
"""add edge u -> v"""
if not u in self.__v:
self.add_vertex(u, udata)
if not v in self.__v:
self.add_vertex(v, vdata)
self.__adj[u].add(v)
if edata is not None:
self.__edata[u][v] = edata
>>>>>>> master
def add_biedge(self, u, v, edata=None):
self.add_edge(u, v, edata)
......@@ -99,14 +123,62 @@ class Digraph(object):
def adj(self, u):
return self.__adj[u]
<<<<<<< HEAD
def get_vertex(self):
=======
def dfs(self, finish_hook = None):
self.color = {}
self.p = {}
self.d = {}
self.f = {}
for u in self.__v:
self.color[u] = 'w' # mark white (unexplored)
self.p[u] = None
self.time = 0
for u in self.__v:
if self.color[u] == 'w':
self.dfs_visit(u, finish_hook)
def dfs_visit(self, u, finish_hook):
self.color[u] = 'g' # mark green (discovered)
self.d[u] = self.time = self.time + 1
for v in self.adj(u):
if self.color[v] == 'w': # explore unexplored vertices
self.p[v] = u
self.dfs_visit(v, finish_hook)
elif self.color[v] == 'g': # cycle detected
cycle = [u]
while self.p[u]:
u = self.p[u]
cycle.append(u)
if self.has_edge(cycle[0], u):
break
cycle.reverse()
raise CycleException(cycle)
self.color[u] = 'b' # mark black (completed)
if finish_hook:
finish_hook(u)
self.f[u] = self.time = self.time + 1
def cycle_free(self):
try:
self.dfs()
return True
except CycleException:
return False
def topological_sort(self):
>>>>>>> master
list = []
for u in self.__v:
list.append(u)
return util.uniq(list)
<<<<<<< HEAD
def sort(self,reverse=False):
return sort.sort_auto(self.get_vertex(),reverse)
=======
>>>>>>> master
@staticmethod
def id_str(u):
# Graph format only accepts underscores as key values
......@@ -122,7 +194,11 @@ class Digraph(object):
f.write('\n')
for u in self.vertices():
for v in self.adj(u):
<<<<<<< HEAD
f.write(self.id_str(u) + ' -> ' + self.id_str(v))
=======
f.write( self.id_str(u) + ' -> ' + self.id_str(v))
>>>>>>> master
self.write_graphviz_elabel(f, u, v)
f.write(';\n')
f.write('\n')
......
......@@ -17,8 +17,11 @@ import gettext
__trans = gettext.translation('inary', fallback=True)
_ = __trans.gettext
<<<<<<< HEAD
from . import *
=======
>>>>>>> master
def invalidate_caches():
# Invalidates inary caches in use and forces to re-fill caches from disk when needed
......
......@@ -85,7 +85,10 @@ class InstallDB(lazydb.LazyDB):
@staticmethod
def __generate_installed_pkgs():
<<<<<<< HEAD
=======
>>>>>>> master
def split_name(dirname):
name, version, release = dirname.rsplit("-", 2)
return name, version + "-" + release
......@@ -156,7 +159,11 @@ class InstallDB(lazydb.LazyDB):
@staticmethod
def __get_version(meta_doc):
<<<<<<< HEAD
package = xmlext.getNode(meta_doc, 'Package')
=======
package = xmlext.getNode(meta_doc,'Package')
>>>>>>> master
history = xmlext.getNode(package, 'History')
update = xmlext.getNode(history, 'Update')
......
......@@ -92,7 +92,13 @@ class ItemByRepo:
for item in list(self.dbobj[r].keys()):
yield str(item), str(self.dbobj[r][item])
<<<<<<< HEAD
def item_repos(self, repo=None):
=======
@staticmethod
def item_repos(repo=None):
repos = inary.db.repodb.RepoDB().list_repos()
>>>>>>> master
if repo:
repos = [repo]
return repos
......
......@@ -78,7 +78,11 @@ class PackageDB(lazydb.LazyDB):
@staticmethod
def __generate_packages(doc):
<<<<<<< HEAD
pdict = {}
=======
pdict={}
>>>>>>> master
for x in xmlext.getTagByName(doc, "Package"):
name = xmlext.getNodeText(x, "Name")
......
......@@ -185,8 +185,14 @@ class RepoDB(lazydb.LazyDB):
def get_repo(self, repo):
return Repo(inary.uri.URI(self.get_repo_url(repo)))
<<<<<<< HEAD
# FIXME: this method is a quick hack around repo_info.indexuri.get_uri()
def get_repo_url(self, repo):
=======
#FIXME: this method is a quick hack around repo_info.indexuri.get_uri()
@staticmethod
def get_repo_url(repo):
>>>>>>> master
urifile_path = util.join_path(ctx.config.index_dir(), repo, "uri")
uri = open(urifile_path).read()
return uri.rstrip()
......
......@@ -38,6 +38,17 @@ import inary.uri
from base64 import encodebytes
<<<<<<< HEAD
=======
try:
import requests
except ImportError:
sys.stdout.write(inary.util.colorize(_("ERROR:\n"),"blinkingred")+ \
_("\tCan't imported requests module.\n"
"\tWhether want the download packages please install\n"
"\t'python3-requests' package from repository.\n"))
from base64 import encodebytes
>>>>>>> master
# For raising errors when fetching
class FetchError(inary.errors.Error):
......@@ -148,8 +159,37 @@ class Fetcher:
self.partial_file = os.path.join(self.destdir, self.url.filename()) + ctx.const.partial_suffix
util.ensure_dirs(self.destdir)
<<<<<<< HEAD
def fetch(self, timeout=100):
=======
self.headers_dict = {'user-agent' : 'Inary Fetcher/' + inary.__version__,
'http-headers' : self._get_http_headers(),
'ftp-headers' : self._get_ftp_headers()
}
def test(self, timeout=3):
try:
requests.get(self.url.get_uri(),
proxies=self._get_proxies(),
timeout=timeout,
headers=self.headers_dict
)
except ValueError as e:
msg = _("Url Problem: \n {}").format(e)
raise FetchError(msg)
except FetchError as e:
msg = _("Can not avaible remote server: \n {}").format(e)
raise FetchError(msg)
return True
def fetch(self, verify=None):
>>>>>>> master
"""Return value: Fetched file's full path.."""
if not ctx.config.values.general.ssl_verify:
......@@ -229,7 +269,11 @@ class Fetcher:
def _get_ftp_headers(self):
headers = []
if self.url.auth_info() and self.url.scheme() == "ftp":
<<<<<<< HEAD
enc = encodebytes('{0}:{0}'.format(self.url.auth_info()).encode('utf-8'))
=======
enc = encodesbytes('{0}:{0}'.format(self.url.auth_info()).encode('utf-8'))
>>>>>>> master
headers.append(('Authorization', 'Basic {}'.format(enc)))
return headers
......
......@@ -179,8 +179,14 @@ class File:
return localfile
<<<<<<< HEAD
def __init__(self, uri, mode, transfer_dir="/tmp",
sha1sum=False, compress=None, sign=None):
=======
def __init__(self, uri, mode, transfer_dir = "/tmp",
sha1sum = False, compress = None, sign = None):
>>>>>>> master
"""it is pointless to open a file without a URI and a mode"""
self.transfer_dir = transfer_dir
......@@ -214,7 +220,11 @@ class File:
"""returns the underlying file object"""
return self.__file__
<<<<<<< HEAD
def close(self, delete_transfer=False): # FIXME: look this parameter
=======
def close(self, delete_transfer = False):
>>>>>>> master
"""this method must be called at the end of operation"""
self.__file__.close()
if self.mode == File.write:
......
......@@ -29,7 +29,10 @@ class autosuprop(autosuper, autoprop):
class autoeq(type):
"""useful for structures"""
<<<<<<< HEAD
=======
>>>>>>> master
def __init__(cls, name, bases, dict):
super(autoeq, cls).__init__(name, bases, dict)
......
......@@ -496,6 +496,10 @@ class Builder:
ctx.const.scom_dir))
ctx.ui.info("Scom Script Fetched {}".format(pscom.script))
<<<<<<< HEAD
=======
>>>>>>> master
@staticmethod
def download(uri, transferdir):
# fix auth info and download
......
......@@ -217,7 +217,11 @@ def install_pkg_files(package_URIs, reinstall=False):
class PackageDB:
@staticmethod
<<<<<<< HEAD
def get_package(key, repo=None):
=======
def get_package(key, repo = None):
>>>>>>> master
return d_t[str(key)]
packagedb = PackageDB()
......
......@@ -127,8 +127,12 @@ def find_upgrades(packages, replaces,packagedb=None,installdb=None):
return Ap
<<<<<<< HEAD
@util.locked
=======
@operations.locked
>>>>>>> master
def upgrade(A=None, repo=None):
"""Re-installs packages from the repository, trying to perform
a minimum or maximum number of upgrades according to options.
......@@ -363,6 +367,52 @@ def plan_upgrade(A, force_replaced=True, replaces=None):
order = G_f.sort()
return G_f, order
<<<<<<< HEAD
=======
def upgrade_base(A=None):
if A is None:
A = set()
installdb = inary.db.installdb.InstallDB()
componentdb = inary.db.componentdb.ComponentDB()
if not ctx.config.values.general.ignore_safety and not ctx.get_option('ignore_safety'):
if componentdb.has_component('system.base'):
systembase = set(componentdb.get_union_component('system.base').packages)
extra_installs = [x for x in systembase - set(A) if not installdb.has_package(x)]
extra_installs = inary.blacklist.exclude_from(extra_installs, ctx.const.blacklist)
if extra_installs:
ctx.ui.warning(_("Safety switch forces the installation of "
"following packages:"))
ctx.ui.info(util.format_by_columns(sorted(extra_installs)))
# Will delete G_F and extra_upgrades
G_f, install_order = operations.install.plan_install_pkg_names(extra_installs)
extra_upgrades = [x for x in systembase - set(install_order) if is_upgradable(x)]
upgrade_order = []
extra_upgrades = inary.blacklist.exclude_from(extra_upgrades, ctx.const.blacklist)
if ctx.get_option('exclude_from'):
extra_upgrades = inary.blacklist.exclude_from(extra_upgrades, ctx.get_option('exclude_from'))
if ctx.get_option('exclude'):
extra_upgrades = inary.blacklist.exclude(extra_upgrades, ctx.get_option('exclude'))
if extra_upgrades:
ctx.ui.warning(_("Safety switch forces the upgrade of "
"following packages:"))
ctx.ui.info(util.format_by_columns(sorted(extra_upgrades)))
G_f, upgrade_order = plan_upgrade(extra_upgrades, force_replaced=False)
#no-need-for-upgrade-order patch
#extra_upgrades = filter(lambda x: is_upgradable(x, ignore_build), systembase - set(extra_installs))
#return set(extra_installs + extra_upgrades)
# return packages that must be added to any installation
return set(install_order + upgrade_order)
else:
ctx.ui.warning(_('Safety switch: The component system.base cannot be found.'))
return set()
>>>>>>> master
def is_upgradable(name):
......
# -*- coding: utf-8 -*-
#
# Main fork Pisi: Copyright (C) 2005 - 2011, Tubitak/UEKAE
#
# Copyright (C) 2016 - 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
class _constant:
"""Constant members implementation"""
class ConstError(TypeError):
pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError("Can't rebind constant: {}".format(name))
# Binding an attribute once to a const is available
self.__dict__[name] = value
def __delattr__(self, name):
if name in self.__dict__:
raise self.ConstError("Can't unbind constant: {}".format(name))
# we don't have an attribute by this name
raise NameError(name)
class Constants:
__c = _constant()
def __getattr__(self, attr):
return getattr(self.__c, attr)
def __setattr__(self, attr, value):
setattr(self.__c, attr, value)
def __delattr__(self, attr):
delattr(self.__c, attr)
consts = Constants()
consts.scenarios_path = "scenarios/"
consts.inary_db = "db/"
consts.repo_name = "scenario-db"
consts.repo_path = "repo/"
consts.repo_url = consts.repo_path + "inary-index.xml"
consts.glob_inarys = "*.inary"
consts.inary_suffix = ".inary"
consts.pspec_path = "/tmp/pspec.xml"
consts.actionspy_path = "/tmp/actions.py"
consts.packager_name = "Faik Uygur"
consts.packager_email = "faik@pardus.org.tr"
consts.homepage = "http://cekirdek.uludag.org.tr/~faik/inary"
consts.summary = "{} is a good application"
consts.description = "{} is a free software that can do anything it wants"
consts.license = ["GPL-2"]
consts.skel_sha1sum = "cc64dfa6e068fe1f6fb68a635878b1ea21acfac7"
consts.skel_type = "targz"
consts.skel_uri = "http://cekirdek.uludag.org.tr/~faik/inary/skeleton.tar.gz"
consts.skel_bindir = "/usr/bin"
consts.skel_dirtype = "executable"
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
#
# Main fork Pisi: Copyright (C) 2005 - 2011, Tubitak/UEKAE
#
# Copyright (C) 2016 - 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import os
import glob
from inary.scenarioapi.pspec import Pspec
from inary.scenarioapi.actions import Actions
from inary.scenarioapi.constants import *
from inary.scenarioapi.withops import *
import gettext
__trans = gettext.translation('inary', fallback=True)
_ = __trans.gettext
class Package:
def __init__(self, name, deps=None, cons=None, date ="2006-18-18", ver ="1.0", partOf="None"):
if deps is None:
deps = []
if cons is None:
cons = []
self.name = name
self.dependencies = deps
self.conflicts = cons
self.version = ver
self.date = date
self.partOf = partOf
self.pspec = None
self.actions = None
self.create_package()
@staticmethod
def create_inary():
os.system("inary build {0} -O {1} > /dev/null 2>&1".format(consts.pspec_path, consts.repo_path))
def create_package(self):
pspec = Pspec(self.name, consts.pspec_path)
pspec.set_source(consts.homepage, consts.summary.format(self.name),
consts.description.format(self.name), consts.license, self.partOf)
pspec.set_packager(consts.packager_name, consts.packager_email)
pspec.add_archive(consts.skel_sha1sum, consts.skel_type, consts.skel_uri)
pspec.set_package(self.dependencies, self.conflicts)
pspec.add_file_path(consts.skel_bindir, consts.skel_dirtype)
pspec.set_history(self.date, self.version)
actions = Actions(self.name, consts.actionspy_path)
self.pspec = pspec
self.actions = actions
self.pspec.write()
self.actions.write()
self.create_inary()
def get_file_name(self):
# use glob. there may be buildnos at the end of the package name
pkg = consts.repo_path + self.name + "-" + \
self.version + "-" + self.pspec.pspec.history[0].release
found = glob.glob(pkg + consts.glob_inarys)
if not found:
raise Exception(_("No inary package: {}* found.").format(pkg))
return os.path.basename(found[0])
def version_bump(self, *args):
for _with in args:
if _with.types == CONFLICT and _with.action == ADDED:
self.pspec.add_conflicts(_with.data)
if _with.types == REQUIRES and _with.action == ADDED:
self.pspec.add_requires(_with.data)
if _with.types == CONFLICT and _with.action == REMOVED:
self.pspec.remove_conflicts(_with.data)
if _with.types == DEPENDENCY and _with.action == ADDED:
self.pspec.add_dependencies(_with.data)
if _with.types == DEPENDENCY and _with.action == REMOVED:
self.pspec.remove_dependencies(_with.data)
if _with.types == VERSION and _with.action == INIT:
self.version = _with.data
self.pspec.update_history(self.date, self.version)
self.pspec.write()
self.actions.name = self.name
self.actions.write()
self.create_inary()
if __name__ == "__main__":
p = Package("w0rmux", [], [], "0.7")
p.version_bump()
......@@ -20,5 +20,6 @@ _ = __trans.gettext
import inary.errors
class Error(inary.errors.Error):
pass
......@@ -107,7 +107,11 @@ class LocalText(dict):
(lang, encoding) = locale.getlocale()
if not lang:
(lang, encoding) = locale.getdefaultlocale()
<<<<<<< HEAD
if lang is None: # stupid python means it is C locale
=======
if lang is None: # stupid python means it is C locale
>>>>>>> master
return 'en'
else:
return lang[0:2]
......@@ -419,7 +423,11 @@ class autoxml(oo.autosuper, oo.autoprop):
def equal(self, other):
# handle None
if other is None:
<<<<<<< HEAD
return False # well, must be False at this point :)
=======
return False # well, must be False at this point :)
>>>>>>> master
for name in names:
try:
if getattr(self, name) != getattr(other, name):
......@@ -437,7 +445,11 @@ class autoxml(oo.autosuper, oo.autoprop):
cls.__ne__ = notequal
if xmlfile_support:
<<<<<<< HEAD
def parse(self, xml, keepDoc=False):
=======
def parse(self, xml, keepDoc = False):
>>>>>>> master
"""parse XML string and decode it into a python object"""
self.parsexml(xml)
errs = []
......@@ -455,14 +467,23 @@ class autoxml(oo.autosuper, oo.autoprop):
if errs:
errs.append(_("autoxml.parse: String '{}' has errors").format(xml))
<<<<<<< HEAD
def read(self, uri, keepDoc=False, tmpDir='/tmp',
sha1sum=False, compress=None, sign=None, copylocal=False, nodecode=False):
=======
def read(self, uri, keepDoc = False, tmpDir = '/tmp',
sha1sum = False, compress = None, sign = None, copylocal = False, nodecode = False):
>>>>>>> master
"""read XML file and decode it into a python object"""
read_xml = self.readxml(uri, tmpDir, sha1sum=sha1sum,
compress=compress, sign=sign, copylocal=copylocal)
if nodecode:
<<<<<<< HEAD
return read_xml
=======
return read_xml
>>>>>>> master
errs = []
self.decode(self.rootNode(), errs)
......@@ -480,8 +501,13 @@ class autoxml(oo.autosuper, oo.autoprop):
errs.append(_("autoxml.read: File '{}' has errors").format(uri))
raise Error(*errs)
<<<<<<< HEAD
def write(self, uri, keepDoc=False, tmpDir='/tmp',
sha1sum=False, compress=None, sign=None):
=======
def write(self, uri, keepDoc = False, tmpDir = '/tmp',
sha1sum = False, compress = None, sign = None):
>>>>>>> master
"""encode the contents of the python object into an XML file"""
errs = self.errors()
if errs:
......@@ -597,7 +623,11 @@ class autoxml(oo.autosuper, oo.autoprop):
"""return errors in the object"""
errs = []
if hasattr(self, name) and getattr(self, name) is not None:
<<<<<<< HEAD
value = getattr(self, name)
=======
value = getattr(self,name)
>>>>>>> master
errs.extend(errors_a(value, where + '.' + name))
else:
if req == mandatory:
......@@ -888,8 +918,16 @@ class autoxml(oo.autosuper, oo.autoprop):
return init, decode, encode, errors, format
basic_cons_map = {
<<<<<<< HEAD
bytes: bytes,
str: str,
int: int,
float: float
}
=======
bytes : bytes,
str : str,
int : int,
float : float
}
>>>>>>> master
......@@ -54,7 +54,11 @@ class UI(object):
def set_debug(self, flag):
self.show_debug = flag
<<<<<<< HEAD
def info(self, msg, verbose=False, noln=False, color='default'):
=======
def info(self, msg, verbose = False, noln = False,color='default'):
>>>>>>> master
"""give an informative message"""
pass
......@@ -67,6 +71,7 @@ class UI(object):
if self.show_debug:
self.info(str('DEBUG: ' + msg))
<<<<<<< HEAD
def warning(self, msg):
"""warn the user"""
pass
......@@ -77,6 +82,18 @@ class UI(object):
# FIXME: merge this with info, this just means "important message"
def action(self, msg):
=======
def warning(self,msg):
"""warn the user"""
pass
def error(self,msg):
"""inform a (possibly fatal) error"""
pass
#FIXME: merge this with info, this just means "important message"
def action(self,msg):
>>>>>>> master
"""uh?"""
pass
......@@ -93,7 +110,11 @@ class UI(object):
"""display progress"""
pass
<<<<<<< HEAD
def status(self, msg=None):
=======
def status(self, msg = None):
>>>>>>> master
"""set status, if not given clear it"""
pass
......
# -*- coding: utf-8 -*-
#
# Main fork Pisi: Copyright (C) 2005 - 2011, Tubitak/UEKAE
#
# Copyright (C) 2016 - 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
# This module is part of inary.util
import gettext
__trans = gettext.translation('inary', fallback=True)
_ = __trans.gettext
import inary
from .file_utils import *
from .package_utils import *
from .path_utils import *
from .process_utils import *
from .term_utils import *
from .type_utils import *
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
This diff is collapsed.
# -*- coding: utf-8 -*-
#
# Main fork Pisi: Copyright (C) 2005 - 2011, Tubitak/UEKAE
#
# Copyright (C) 2016 - 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
# This module is part of inary.util
import inary.context as ctx
import os
import sys
import fcntl
import struct
import termios
import gettext
__trans = gettext.translation('inary', fallback=True)
_ = __trans.gettext
######################
# Terminal functions #
######################
def get_terminal_size():
try:
ret = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, "1234")
except IOError:
rows = int(os.environ.get("LINES", 25))
cols = int(os.environ.get("COLUMNS", 80))
return rows, cols
return struct.unpack("hh", ret)
def xterm_title(message):
"""Set message as console window title."""
if "TERM" in os.environ and sys.stderr.isatty():
terminalType = os.environ["TERM"]
for term in ["xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"]:
if terminalType.startswith(term):
sys.stderr.write("\x1b]2;"+str(message)+"\x07")
sys.stderr.flush()
break
def xterm_title_reset():
"""Reset console window title."""
if "TERM" in os.environ:
xterm_title("")
def colorize(msg, color):
"""Colorize the given message for console output"""
if color in ctx.const.colors and not ctx.get_option('no_color'):
return str(ctx.const.colors[color] + msg + ctx.const.colors['default'])
else:
return str(msg)
def format_by_columns(strings, sep_width=2):
longest_str_len = len(max(strings, key=len))
term_rows, term_columns = get_terminal_size()
def get_columns(max_count):
if longest_str_len > term_columns:
return [longest_str_len]
columns = []
for name in strings:
table_width = sum(columns) + len(name) + len(columns) * sep_width
if table_width > term_columns:
break
columns.append(len(name))
if len(columns) == max_count:
break
return columns
def check_size(columns):
total_sep_width = (len(columns) - 1) * sep_width
for n, name in enumerate(strings):
col = n % len(columns)
if len(name) > columns[col]:
columns[col] = len(name)
if len(columns) > 1:
width = sum(columns) + total_sep_width
if width > term_columns:
return False
return True
columns = get_columns(term_columns)
while not check_size(columns):
columns = get_columns(len(columns) - 1)
sep = " " * sep_width
lines = []
current_line = []
for n, name in enumerate(strings):
col = n % len(columns)
current_line.append(name.ljust(columns[col]))
if col == len(columns) - 1:
lines.append(sep.join(current_line))
current_line = []
if current_line:
lines.append(sep.join(current_line))
return "\n".join(lines)
This diff is collapsed.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Main fork Pisi: Copyright (C) 2005 - 2011, Tubitak/UEKAE
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
import os
import sys
import glob
import string
import shutil
import inary.util as util
from inary.version import Version
def findUnneededFiles(listdir):
dict = {}
for f in listdir:
try:
name, version = util.parse_package_name(f)
if name in dict:
if Version(dict[name]) < Version(version):
dict[name] = version
else:
if version:
dict[name] = version
except:
pass
for f in dict:
listdir.remove("%s-%s" % (f, dict[f]))
return listdir
def doit(root, listdir, clean, suffix = ""):
for f in listdir:
target = os.path.join(root, "%s%s" % (f, suffix))
if os.path.exists(target):
print(("%s%s" % (f, suffix)))
if clean:
try:
if os.path.isdir(target):
shutil.rmtree(target)
else:
os.remove(target)
except OSError as e :
usage("Permission denied: %s" % e)
def cleanInarys(clean, root = '/var/cache/inary/packages'):
# inary packages
list = [os.path.basename(x).split(".inary")[0] for x in glob.glob("%s/*.inary" % root)]
list.sort()
l = findUnneededFiles(list)
doit(root, l, clean, ".inary")
def cleanBuilds(clean, root = '/var/inary'):
# Build remnant
list = []
for f in os.listdir(root):
if os.path.isdir(os.path.join(root, f)):
list.append(f)
l = findUnneededFiles(list)
doit(root, l, clean)
def usage(msg):
print(("""
Error: %s
Usage:
cleanCache --dry-run (Shows unneeded files)
cleanCache --clean (Removes unneeded files)
""" % msg))
sys.exit(1)
if __name__ == "__main__":
try:
sys.argv[1]
except IndexError:
usage("Unsufficient arguments...")
if "--dry-run" in sys.argv:
clean = False
elif "--clean" in sys.argv:
clean = True
else:
usage("No command given...")
sys.exit(0)
if "builds" in sys.argv:
cleanBuilds(clean)
else:
cleanInarys(clean)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Main fork Pisi: Copyright (C) 2005 - 2011, Tubitak/UEKAE
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
import os
import sys
from zipfile import BadZipfile
from inary.package import Package
def usage(errmsg):
print(("""
Error: %s
Usage:
uninary INARY_package.inary [target_dir]
""" % (errmsg)))
sys.exit(1)
def main():
if len(sys.argv) < 2:
usage("INARY package required..")
elif not os.path.exists(sys.argv[1]):
usage("File %s not found" % sys.argv[1])
try:
package = Package(sys.argv[1])
except BadZipfile as e:
print(e)
sys.exit(1)
if not os.path.exists("install"):
os.makedirs("install")
target = '.' if len(sys.argv) == 2 else sys.argv[2]
package.extract_inary_files(target)
package.extract_dir('comar', target)
if not os.path.exists(os.path.join(target, 'install')):
os.makedirs(os.path.join(target, 'install'))
package.extract_install(os.path.join(target, 'install'))
# FIXME: There is a Inary bug, it already creates an install directory even its empty.
if not os.listdir('install'):
os.rmdir('install')
return 0
if __name__ == "__main__":
sys.exit(main())
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment