Сегодня 6 июля, воскресенье ГлавнаяНовостиО проектеЛичный кабинетПомощьКонтакты Сделать стартовойКарта сайтаНаписать администрации
Поиск по сайту
 
Ваше мнение
Какой рейтинг вас больше интересует?
 
 
 
 
 
Проголосовало: 7281
Кнопка
BlogRider.ru - Каталог блогов Рунета
получить код
Евгений Ламской
Евгений Ламской
Голосов: 1
Адрес блога: http://lamskoy.livejournal.com/
Добавлен: 2010-05-18 17:01:15
 

Утилита для выбора зеркал пакетов в Archlinux

2010-09-22 16:35:23 (читать в оригинале)

Вот и обещанная утилита, которая выбирает зеркала пакетов в Archlinux.

Выбирает она не отдельные зеркала, а группами - по странам

Выглядит она так:

Требования: PHP 5.2.x (с отключенным open_basedir, safe_mode и разрешенным вызовом exec()), dialog

Запускается так:

sudo php mirrorselect.php

Ниже приведен исходный код

<?php


class Mirrorlist
{
    protected $_filename;
    protected $_data;

    public function __construct()
    {
        $this->_data = array();
        $this->_filename = false;
    }

    public function read($filename)
    {       
        if(!is_file($filename) || !is_readable($filename)) {
            throw new Exception ("Cannot read file: $filename");
        }
        $this->_filename = $filename;
        $f = fopen($this->_filename, 'r');
        $currentTitle = '';

        while(!feof($f)) {
            $line = fgets($f, 1024);

            $isServer = preg_match("/^[\s]?([#]?)[\s]?Server[\s]+=[\s]+([^\s]+)[\s]?$/", $line, $serverMatches);     
            $isTitle = $isServer ? false : preg_match("/^[\s]?#[\w\s]+$/i", $line, $titleMatches);
            $trimmed = trim(ltrim($line, "#"));

            if(!$trimmed) {
                continue;
            }
           
            if($isTitle) {
                $currentTitle = $trimmed;
            } elseif ($isServer) {
                $active = empty($serverMatches[1]);
                $uri = $serverMatches[2];
                $title = $currentTitle ? $currentTitle : "Custom servers";
                if(!isset($this->_data[$title])) {
                   $this->_data[$title] = array ( 'servers' => array(), 'allactive' => true, 'count' => 0 );
                }
                $this->_data[$title]['count']++;
                $this->_data[$title]['servers'][$uri] = $active;
                if($active == false) {
                    $this->_data[$title]['allactive'] = false;
                }
            }         
        }       
        fclose($f);             
        return $this;
    }

    public function __toString()
    {
        if(!count($this->_data)) {
            return '';
        }

        $data = "# Selectmirror generated \n\n";
        foreach($this->_data as $country=>$cdata) {
            if(!$data['servers']) {
                continue;
            }
            $data .= "# $country\n";
            foreach($cdata['servers'] as $uri=>$enabled) {
                $data .= ($enabled ? '' : '#') . "Server = " . $uri . "\n";
            }       
            $data .= "\n\n";
        }
        return $data;
    }

    public function save($filename = false)
    {   
        if(false == $filename) {
            $filename = $this->_filename;
        }
        if(false === $filename) {
            return $this;
        }       
        if (false === file_put_contents($filename, $this->__toString())) {
            throw new Exception ("Cannot write to file: $filename");
        }
        return $this;       
    }

    public function getCountriesList()
    {
        return $this->_data;
    }

    public function setEnabledCountries($countries, $disableRest = true)
    {
        if(!$countries) {
           return $this;
        }               
        $countries = (array) $countries;

        foreach($this->_data as $c => $data) {
            foreach($this->_data[$c]['servers'] as $k=>$v) {
                if(in_array($c, $countries)) {
                    $this->_data[$c]['servers'][$k] = true;
                    $this->_data[$c]['allactive'] = true;
                } elseif($disableRest) {
                    $this->_data[$c]['servers'][$k] = false;
                    $this->_data[$c]['allactive'] = false;
                }             
            }
        }
        return $this;
    }
}

class DialogMirrorlist extends Mirrorlist
{
    public function getCommand()
    {
        if(!count($this->_data)) {
            return false;
        }
        $command = "dialog --checklist --stdout \"Select countries closest to you\" 0 0 0 ";
        foreach($this->_data as $name => $data) {
            $count = $data['count'];
            $active = $data['allactive'] ? 'on' : 'off';
            $command .= " \"${name}\" \"Mirrors count: ${count}\" $active ";
        }
        return $command;
    }

    public function setEnabledCountries($countriesString, $disableRest = true)
    {
        $countriesList = preg_split('/"[\s]+"/', trim($countriesString, '"'));
        return parent::setEnabledCountries($countriesList, $disableRest);
    }
}

class App {

    public static function exec($cmd)
    {
        $outArr = array()
        $returnInt = null;
        $out = exec(escapeshellcmd($cmd), $outArr, $returnInt);
        return array('code'=> (int) $returnInt, 'out' => $out, 'all' =>$outArr);

    }

    public static function findOnPath($cmd)
    {
        $return = self::exec("which $cmd");
        return $return['code'] == 0;
    }

    public static function checkRequirements()
    {
        if(ini_get('open_basedir')) {
            throw new Exception("Set open_basedir = Off directive in your php.ini before using this script.");
        }
        if(!function_exists("exec")) {
           throw new Exception("exec() function is disabled in PHP. Can't work without it's support.");
        }
        if(!self::findOnPath('dialog')) {
            throw new Exception("dialog utility is not found on path");
        }
    }

    public static function run()
    {
        try {
            self::checkRequirements();

            $mirrors = new DialogMirrorlist();
            $command = $mirrors->read('/etc/pacman.d/mirrorlist')->getCommand();
           
            if(!$command) {
                echo "No mirrors detected it given mirrorlist. Nothing to do. \n";
                exit(0);
            }       

            $return = self::exec($command);
            if($return['code'] == 0) {
                $mirrors->setEnabledCountries($return['out'])->save();         
            }                             

            exit(0);

        } catch (Exception $e) {
          echo "Error: {$e->getMessage()} \n";
          exit(1);
        }
    }   
}

App::run();Syhi-подсветка кода



 


Самый-самый блог
Блогер ЖЖ все стерпит
ЖЖ все стерпит
по сумме баллов (758) в категории «Истории»


Загрузка...Загрузка...
BlogRider.ru не имеет отношения к публикуемым в записях блогов материалам. Все записи
взяты из открытых общедоступных источников и являются собственностью их авторов.