Example #1
0
def runTest(tFile, level=None, delete=True, outDir=outDirDefault):
	passed = True
	if level == None:
		for x in range(1, 10):
			if runTest(tFile, x, delete) == False:
				passed = False

		return passed

	# make the test-outs directory
	try:
		os.mkdir(outDir)
	except:
		pass

	out1 = os.path.join(outDir, '%(file)s.%(level)d.deflate' % {'file': os.path.basename(tFile), 'level' : level})
	out2 = os.path.join(outDir, '%(file)s.%(level)d.out.deflate' % {'file': os.path.basename(tFile), 'level' : level})

	outData = deflate(tFile, outfile=out1, level=level)
	run_cmd('../bin/deflate.js --level %(level)d --file %(file)s --output %(output)s' % {'level' : level, 'file' : tFile, 'output' : out2})

	result = run_cmd('diff %(file1)s %(file2)s' % {'file1' : out1, 'file2' : out2})
	if result['returncode'] == 0:
		status = Fore.GREEN + 'PASSED' + Fore.RESET
	else:
		passed = False
		status = Fore.RED + 'FAILED' + Fore.RESET
	
	print 'Level %(level)d: %(status)s' % {'level' : level, 'status' : status}

	if delete == True:
		os.remove(out1)
		os.remove(out2)

	return passed
Example #2
0
def runTest(tFile, level=None, outDir=defaultOutDir):
	passed = True
	if level == None:
		for x in range(1, 10):
			if runTest(tFile, x, outDir) == False:
				passed = False

		return passed

	out1 = os.path.join(outDir, '%(file)s.%(level)d.gz' % {'file': os.path.basename(tFile), 'level' : level})
	out2 = os.path.join(outDir, '%(file)s.%(level)d.out.gz' % {'file': os.path.basename(tFile), 'level' : level})

	run_cmd('gzip -c -%(level)d %(file)s > %(outfile)s' % {'level' : level, 'file' : tFile, 'outfile' : out1})
	run_cmd('../bin/gzip.js --level %(level)d --file %(file)s --output %(output)s' % {'level' : level, 'file' : tFile, 'output' : out2})

	result = run_cmd('diff %(file1)s %(file2)s' % {'file1' : out1, 'file2' : out2})
	if result['returncode'] == 0:
		status = Fore.GREEN + 'PASSED' + Fore.RESET
	else:
		passed = False
		status = Fore.RED + 'FAILED' + Fore.RESET
	
	print 'Level %(level)d: %(status)s' % {'level' : level, 'status' : status}

	return passed
Example #3
0
def get_clither():
  """Get clither."""
  print('Getting clither...')

  if os.path.exists(paths.clither_path):
    run_cmd(cd(paths.clither_path), 'git pull')
    return

  run_cmd(cd(paths.base_dir), 'git clone ' + paths.clither_base_repo)
def runTest(tFile, level=None, delete=True, outDir=outDirDefault):
    passed = True
    if level == None:
        for x in range(1, 10):
            if runTest(tFile, x, delete) == False:
                passed = False

        return passed

    # make the test-outs directory
    try:
        os.mkdir(outDir)
    except:
        pass

    out1 = os.path.join(
        outDir, '%(file)s.%(level)d.deflate' % {
            'file': os.path.basename(tFile),
            'level': level
        })
    out2 = os.path.join(
        outDir, '%(file)s.%(level)d.out.deflate' % {
            'file': os.path.basename(tFile),
            'level': level
        })

    outData = deflate(tFile, outfile=out1, level=level)
    run_cmd(
        '../bin/deflate.js --level %(level)d --file %(file)s --output %(output)s'
        % {
            'level': level,
            'file': tFile,
            'output': out2
        })

    result = run_cmd('diff %(file1)s %(file2)s' % {
        'file1': out1,
        'file2': out2
    })
    if result['returncode'] == 0:
        status = Fore.GREEN + 'PASSED' + Fore.RESET
    else:
        passed = False
        status = Fore.RED + 'FAILED' + Fore.RESET

    print 'Level %(level)d: %(status)s' % {'level': level, 'status': status}

    if delete == True:
        os.remove(out1)
        os.remove(out2)

    return passed
Example #5
0
  def process_node(cmd_name):
    if cmd_name not in desired_cmds:
      raise Exception('{0} is not defined.'.format(cmd_name))
    
    if cmd_name in has_been_processed:
      return

    _type, deps, to_install, to_update =  desired_cmds[cmd_name]

    if not any([deps, to_install, to_update]):
      return

    for dep in deps:
      if dep not in has_been_processed:
        process_node(dep)
    
    run_install = True  # tmp until get logic for script

    if _type == 'path':
      path_exes = get_installed_exe()
      run_install = cmd_name not in path_exes

    lock_file = os.path.basename(addon_path)
    cmd_name = cmd_name.replace(' ', "-")
    lock_file = '{0}-{1}.{2}'.format(lock_file, cmd_name, 'installed')
    lock_file = os.path.join(paths.custom_lockfile_path, lock_file)
    if _type == 'install' and os.path.exists(lock_file):
      run_install = False

    cmd = None
    if run_install and to_install:
      cmd = to_install

    if not run_install and to_update:
      cmd = to_update

    if not cmd and _type == 'install':
      return

    if not cmd:
      msg = ('{0} line is malformed. Look into it.')
      raise Exception(msg.format(cmd_name))

    cmd = cmd.format(addon_path)

    run_cmd(cmd)
    has_been_processed.append(cmd_name)

    if _type == 'install' and not os.path.exists(lock_file):
      clear_file(lock_file)
Example #6
0
def runTest(tFile, level=None, outDir=defaultOutDir):
    passed = True
    if level == None:
        for x in range(1, 10):
            if runTest(tFile, x, outDir) == False:
                passed = False

        return passed

    out1 = os.path.join(
        outDir, '%(file)s.%(level)d.gz' % {
            'file': os.path.basename(tFile),
            'level': level
        })
    out2 = os.path.join(
        outDir, '%(file)s.%(level)d.out.gz' % {
            'file': os.path.basename(tFile),
            'level': level
        })

    run_cmd('gzip -c -%(level)d %(file)s > %(outfile)s' % {
        'level': level,
        'file': tFile,
        'outfile': out1
    })
    run_cmd(
        '../bin/gzip.js --level %(level)d --file %(file)s --output %(output)s'
        % {
            'level': level,
            'file': tFile,
            'output': out2
        })

    result = run_cmd('diff %(file1)s %(file2)s' % {
        'file1': out1,
        'file2': out2
    })
    if result['returncode'] == 0:
        status = Fore.GREEN + 'PASSED' + Fore.RESET
    else:
        passed = False
        status = Fore.RED + 'FAILED' + Fore.RESET

    print 'Level %(level)d: %(status)s' % {'level': level, 'status': status}

    return passed
Example #7
0
def clone_addons(addons):
  """Clone addons.

  args:
    addons: (list) Addons to clone.
  """
  print('Cloning addons...')

  used_addons = set()
  for url in addons:
    addon_name = os.path.basename(url)

    git_repo_comp = re.compile(r'https?://(.+?)(.git)*$')
    match = git_repo_comp.match(url)

    trucated_url = addon_name
    if match:
      trucated_url , _ = match.groups()

    new_addon_name = get_new_path(
       trucated_url, paths.custom_addons_path, '')

    print('add ' + new_addon_name)
    used_addons.add(new_addon_name)
    if os.path.exists(new_addon_name):
      run_cmd(cd(new_addon_name), 'git pull')
      continue

    run_cmd(cd(paths.custom_addons_path), 'git clone ' +  url)
    addon_path = os.path.join(paths.custom_addons_path, addon_name)

    os.rename(addon_path, new_addon_name)  #TODO(xnz): absract to helper
    print('rename {0} to {1}'.format(addon_path, new_addon_name))

  existing_addons = set(
    os.path.join(paths.custom_addons_path, entry) 
    for entry in get_dir_list(paths.custom_addons_path))

  extra_addons = existing_addons - used_addons
  if extra_addons:
    print('You have untracked addons: ' + ', '.join(extra_addons))
Example #8
0
def run_command(command, no_run):
    """

    Parameters
    ----------
    command : `list`
        The command to run.
    no_run : `bool`
        Flag for deciding if to run the command.
    """
    print(f"{' '.join(command)}")
    if not no_run:
        output = hp.run_cmd(command)
        print(output)
def run_command(command, no_run):
    """

    Parameters
    ----------
    command : `list`
        The command to run.
    no_run : `bool`
        Flag for deciding if to run the command.
    """
    print(f"{' '.join(command)}")
    if not no_run:
        output = hp.run_cmd(command, as_lines=True)
        # Last entry is empty so don't send.
        return output[:-1]
Example #10
0
def get_file_digest(fn):
    u'''
    Получение текстового представления хэш-кода переданного файла
    по ГОСТ Р 34.11-94.

    :param unicode fn: Путь к файлу, хэш-код которого необходимо получить.
    :return: Закодированный в base64 хэш-код текста.
    :rtype: unicode
    '''
    openssl_sign_cmd = ['openssl', 'dgst', '-binary', '-md_gost94', fn]

    out, err = run_cmd(openssl_sign_cmd)
    if err:
        raise ValueError(u'OpenSSL error: %s' % err)

    return base64.b64encode(out)
Example #11
0
def get_file_digest(fn):
    u'''
    Получение текстового представления хэш-кода переданного файла
    по ГОСТ Р 34.11-94.

    :param unicode fn: Путь к файлу, хэш-код которого необходимо получить.
    :return: Закодированный в base64 хэш-код текста.
    :rtype: unicode
    '''
    openssl_sign_cmd = ['openssl', 'dgst', '-binary', '-md_gost94', fn]

    out, err = run_cmd(openssl_sign_cmd)
    if err:
        raise ValueError(u'OpenSSL error: %s' % err)

    return base64.b64encode(out)
Example #12
0
def main(opts):
    username, password = get_credentials(opts.token_file)

    cmd = [
        "argocd",
        "login",
        "--plaintext",
        "--port-forward",
        "--port-forward-namespace",
        "argocd",
        "--username",
        f"{username}",
        "--password",
        f"{password}",
    ]

    output = hp.run_cmd(cmd)
    print(output)
Example #13
0
def load_pubkey_from_pem(data):
    u'''
    Загрузка данных публичного ключа из PEM-контейнера
    (RFC 1421-1424).

    :param unicode pem_filename: Имя файла PEM-контейнера.
    :return: base64-представление данных публичного ключа.
    :rtype: unicode
    '''

    assert data, 'No PEM provided!'

    load_key_cmd = ['openssl', 'x509', '-inform', 'PEM', '-pubkey', '-noout']

    out, err = run_cmd(load_key_cmd, input=data)

    if err:
        raise SignerError(unicode(err))

    return out
Example #14
0
def load_pubkey_from_pem(data):
    u'''
    Загрузка данных публичного ключа из PEM-контейнера
    (RFC 1421-1424).

    :param unicode pem_filename: Имя файла PEM-контейнера.
    :return: base64-представление данных публичного ключа.
    :rtype: unicode
    '''

    assert data, 'No PEM provided!'

    load_key_cmd = ['openssl', 'x509', '-inform', 'PEM', '-pubkey', '-noout']

    out, err = run_cmd(load_key_cmd, input=data)

    if err:
        raise SignerError(unicode(err))

    return out
Example #15
0
def get_text_signature(text, private_key_fn, private_key_pass):
    u'''
    Получение ЭП указанного текста через вызов внешнего экземпляра OpenSSL,
    с использованием частного ключа ОИВ.

    :param unicode text: Подписываемый текст.
    :param unicode private_key_fn: Путь к PEM-файлу, содержащему частный ключ.
    :param unicode private_key_pass: Пароль к частному ключу.

    :return: Закодированная в base64 ЭП текста.
    :rtype: unicode
    '''
    openssl_sign_cmd = [
        'openssl', 'dgst', '-sign', private_key_fn, '-binary',
        '-md_gost94', '-passin', 'stdin']

    out, err = run_cmd(openssl_sign_cmd, input=private_key_pass + '\n' + text)
    if err:
        raise ValueError(u'OpenSSL error: %s' % err)

    return base64.b64encode(out)
Example #16
0
def get_text_signature(text, private_key_fn, private_key_pass):
    u'''
    Получение ЭП указанного текста через вызов внешнего экземпляра OpenSSL,
    с использованием частного ключа ОИВ.

    :param unicode text: Подписываемый текст.
    :param unicode private_key_fn: Путь к PEM-файлу, содержащему частный ключ.
    :param unicode private_key_pass: Пароль к частному ключу.

    :return: Закодированная в base64 ЭП текста.
    :rtype: unicode
    '''
    openssl_sign_cmd = [
        'openssl', 'dgst', '-sign', private_key_fn, '-binary', '-md_gost94',
        '-passin', 'stdin'
    ]

    out, err = run_cmd(openssl_sign_cmd, input=private_key_pass + '\n' + text)
    if err:
        raise ValueError(u'OpenSSL error: %s' % err)

    return base64.b64encode(out)
Example #17
0
def verify_gost94_signature(text, public_key, signature_value):
    u'''
    Проверка корректности ЭП переданного текста по ГОСТ Р 34.11-94.

    :param unicode text: Текст, подпись которого проверяется.
    :param unicode public_key: Публичный ключ, которым подписывался текст.
    :param unicode signature_value: Подпись.

    :return: Флаг корректности ЭП текста.
    :type: boolean
    '''

    # Так как OpenSSL не умеет считывать значения подписи и проверяемый
    # текст со стандартного ввода, мы вынуждены использовать временные файлы.
    # После записи они закрываются, т.к. Windows не позволяет считывать
    # открытые файлы.
    tmp_public_key = NamedTemporaryFile(delete=False)
    tmp_public_key.file.write(public_key)
    tmp_public_key.file.close()

    tmp_signature_value = NamedTemporaryFile(delete=False)
    tmp_signature_value.file.write(base64.b64decode(signature_value))
    tmp_signature_value.file.close()

    openssl_sign_cmd = [
        'openssl', 'dgst', '-md_gost94', '-verify', tmp_public_key.name,
        '-signature', tmp_signature_value.name
    ]

    out, err = run_cmd(openssl_sign_cmd, input=text)

    if err:
        raise SignerError(unicode(err))

    # Убираем за собой
    os.remove(tmp_signature_value.name)
    os.remove(tmp_public_key.name)

    return out.strip() == "Verified OK"
Example #18
0
def verify_gost94_signature(text, public_key, signature_value):
    u'''
    Проверка корректности ЭП переданного текста по ГОСТ Р 34.11-94.

    :param unicode text: Текст, подпись которого проверяется.
    :param unicode public_key: Публичный ключ, которым подписывался текст.
    :param unicode signature_value: Подпись.

    :return: Флаг корректности ЭП текста.
    :type: boolean
    '''

    # Так как OpenSSL не умеет считывать значения подписи и проверяемый
    # текст со стандартного ввода, мы вынуждены использовать временные файлы.
    # После записи они закрываются, т.к. Windows не позволяет считывать
    # открытые файлы.
    tmp_public_key = NamedTemporaryFile(delete=False)
    tmp_public_key.file.write(public_key)
    tmp_public_key.file.close()

    tmp_signature_value = NamedTemporaryFile(delete=False)
    tmp_signature_value.file.write(base64.b64decode(signature_value))
    tmp_signature_value.file.close()

    openssl_sign_cmd = ['openssl', 'dgst', '-md_gost94', '-verify',
                        tmp_public_key.name, '-signature',
                        tmp_signature_value.name]

    out, err = run_cmd(openssl_sign_cmd, input=text)

    if err:
        raise SignerError(unicode(err))

    # Убираем за собой
    os.remove(tmp_signature_value.name)
    os.remove(tmp_public_key.name)

    return out.strip() == "Verified OK"
Example #19
0
# /output/output contains a dotnet project with the generated stubs
projectNameOut = "output"
projectDirOut = os.path.join(outputDir, projectNameOut)

# /db contains the extracted QL DB
dbName = 'db'
dbDir = os.path.join(workDir, dbName)
outputName = "stub"
outputFile = os.path.join(projectDirOut, outputName + '.cs')
bqrsFile = os.path.join(rawOutputDir, outputName + '.bqrs')
jsonFile = os.path.join(rawOutputDir, outputName + '.json')
version = helpers.get_argv(2, "latest")

print("\n* Creating new input project")
helpers.run_cmd(['dotnet', 'new', 'classlib', "--language", "C#", '--name',
                 projectNameIn, '--output', projectDirIn])
helpers.remove_files(projectDirIn, '.cs')

print("\n* Adding reference to package: " + nuget)
cmd = ['dotnet', 'add', projectDirIn, 'package', nuget]
if (version != "latest"):
    cmd.append('--version')
    cmd.append(version)
helpers.run_cmd(cmd)

print("\n* Creating DB")
helpers.run_cmd(['codeql', 'database', 'create', dbDir, '--language=csharp',
                 '--command', 'dotnet build /t:rebuild ' + projectDirIn])

if not os.path.isdir(dbDir):
    print("Expected database directory " + dbDir + " not found.")
Example #20
0
 def _clone_repo(self):
     cmd = ["git", "clone", self._index_git, self._clone_path]
     if path.exists(self._clone_path):
         rmtree(self._clone_path)
     run_cmd(cmd)
Example #21
0
 def __convert(self):
     self.xml_file = tmpfile(prefix=APP_CMD, suffix='.xml')
     cmd = '{} -c -i -hidden -xml {} {}'.format(self.convert_cmd, self.pdf_file, self.xml_file)
     if not run_cmd(cmd=cmd):
         rmfile(self.xml_file)
         raise ParsePDFConvertError('Unable to convert PDF file: %s' % self.pdf_file)
Example #22
0
 def _clone_repo(self):
     cmd = ["git", "clone", self._index_git, self._clone_path]
     if path.exists(self._clone_path):
         rmtree(self._clone_path)
     run_cmd(cmd)
Example #23
0
def run_clither(args):
  flags = ' '.join(args)
  if not args:
    flags = '--setup_custom --install'
  run_cmd(cd(paths.clither_path), './clither.py ' + flags)
Example #24
0
def correct_word(word, corrector):
    corrected = run_cmd(f"bash predict.sh {corrector} {word}")

    return corrected.strip()