function cmdRepo()
 {
     $file = new File('/home/billy/1.tar.bz2', true);
     $target = new Dir('/home/billy/temp/1.unpack/includes', true);
     //Packer::unpack($file, $target);
     Packer::pack($target, new File(dirname(__FILE__) . '/2.tbz', true));
     return;
     $pm = new PM();
     $pm->startup();
     $rb = PM::getRollback();
     $rb->push('delete', dirname(__FILE__) . '/_files/source', dirname(__FILE__) . '/_files/target/includes/Controller.php');
     //$rb->push('delete', './_files/source', '_files/target/includes/Controller.php' );
     //$r = $rb->pop();
     $r = $rb->stepBack();
     print_r($r);
     return;
     $ps = PM::getPackageSequence();
     print_r($ps->get());
     print_r($ps->getAfter('news', '2.3'));
     //print_pre($ps->addPackage('news', '2.8'));
     print_pre($ps->removePackage('news', '2.8'));
     return;
     Autoload::addDir(Dir::get($this->root, true)->getDir('repo'));
     $rl = new RepositoryList($this->dataDir->getFile('source.list'));
     $r = $rl->search(explode(' ', 'qt package'));
     print_pre($r);
     $pm->shutdown();
 }
Exemple #2
0
 /**
  *
  *
  */
 function __construct($fileOrXml, $urls = null)
 {
     //io::out('Package __construct: '.(is_null($urls)?$fileOrXml:implode(', ',$urls)));
     $this->xml = new DomDocument();
     try {
         if ($fileOrXml instanceof iFile) {
             $packageFile = $fileOrXml;
             if (!$packageFile->exists()) {
                 throw new PackageException('PackageFile(' . $packageFile . ') not exists.');
             }
             $tmpDir = Dir::get(Config::getInstance()->root_dir, true)->getDir(Config::getInstance()->temp_dir);
             $xmlFile = Packer::unpackFile($packageFile, $tmpDir, 'package.xml');
             $this->xml->load($xmlFile);
             $this->file = $packageFile;
             $this->status = $this->determineStatus();
         } else {
             if (!is_array($urls) || count($urls) == 0) {
                 throw new PackageException('Cant create package: list of URLs not set or empty.');
             }
             $this->urls = $urls;
             $this->xml->appendChild($this->xml->importNode($fileOrXml, true));
             $this->status = Package::FOUNDED;
         }
         // TODO Валидировать xml-schemas
         $this->name = $this->xml->getElementsByTagName('name')->item(0)->nodeValue;
         $this->version = $this->xml->getElementsByTagName('version')->item(0)->nodeValue;
     } catch (DOMException $e) {
         throw PackageException('Error while processing or parsing xml file with Message:' . $e->getMessage());
     }
 }
Exemple #3
0
 /**
  *
  */
 static function getDir($storageName)
 {
     static $dir = null;
     if (is_null($dir)) {
         $dir = Dir::get(Config::get('ROOT_DIR') . Config::get('STORAGE_DIR'), true);
         TTL::init();
     }
     return $dir->getDir('data/' . $storageName);
 }
Exemple #4
0
 public function dsGetSrc()
 {
     $html = Dir::get('html/markdown');
     $src = 'help.' . Language::currentName() . '.html';
     if (!$html->getFIle($src)->exists()) {
         $src = 'help.en.html';
     }
     $r = new ResultSet();
     return t(new ResultSet())->f('#help')->text(file_get_contents($html->getFile($src)));
 }
Exemple #5
0
 /**
  *
  */
 static function pack(Dir $source, File $target)
 {
     if (!$source->exists()) {
         throw new PackerException('Source folder ' . $source . ' not readable.');
     }
     if (!$target->getParent()->canWrite()) {
         throw new PackerException('Target file ' . $target . ' not writable.');
     }
     $cmd = str_replace(array('{FILE}', '{TARGET}'), array($source, $target), self::$config['pack_template']);
     exec($cmd, $out, $res);
     if ($res) {
         $out[] = PHP_EOL . 'Exit code: ' . $res . PHP_EOL;
         $f = Dir::get(Config::getInstance()->root_dir, true)->getDir(self::$config['logDir'])->getFile('pack_' . basename($source) . '.log');
         file_put_contents($f, implode(PHP_EOL, $out));
         throw new PackerException('Error while unpacking. Return code: ' . $res . '. Log file stored at ' . $f);
     }
 }
Exemple #6
0
 /**
  * Обработка одного шага.
  *
  * @throw RollbackException
  * @param array $step
  */
 function processStep($step)
 {
     if (!count($step)) {
         return;
     }
     switch ($cmd = array_shift($step)) {
         case 'delete':
             $this->delete($step);
             break;
         case 'move':
             break;
         case 'undeploy':
             Deployer::undeploy(Dir::get($step[0], true));
             break;
         default:
             throw new RollbackException('Unknown command ' . $cmd);
     }
     return true;
 }
Exemple #7
0
 /**
  * Разбирает $this->node, возвращает массив операций
  *
  * @return array 
  */
 private function parseNode()
 {
     if (!is_null($this->node->attributes->getNamedItem('file'))) {
         $fileName = $this->node->attributes->getNamedItem('file')->nodeValue;
     } else {
         $fileName = basename(Config::getInstance()->getParsedFilename());
     }
     $this->file = Dir::get(Config::getInstance()->root_dir, true)->getDir('config')->getFile($fileName);
     // записываем полный путь файла для отката
     file_put_contents($this->rollbackDir->getFile('config.txt'), $this->file);
     $ops = array();
     $op = $this->node->childNodes;
     for ($i = 0; !is_null($item = $op->item($i++));) {
         if (method_exists($this, $item->nodeName)) {
             $ops[] = array('operation' => $item->nodeName, 'param' => $this->nodeToArray($item));
         }
     }
     return $ops;
 }
Exemple #8
0
 static function upload($post, $path)
 {
     $uf = t(new UploadedFiles("uploaded_file"))->count(1)->onlyImages();
     if (!empty($post->upload_rename)) {
         $uf->setFileName($post->upload_rename, "uploaded_file");
     }
     $ipath = implode("/", $path);
     $d = Dir::get(self::ROOT)->getDir(implode("/", $path))->upload($uf);
 }
Exemple #9
0
 static function undeploy($dir)
 {
     io::out('Undeploying => ~GRAY~' . substr($dir, strlen(Config::getInstance()->root_dir)) . '~~~: ');
     $fu = new FileUpdater(Dir::get(Config::getInstance()->root_dir, true), self::restoreTargetPath($dir), $dir);
     $fu->undo();
 }
Exemple #10
0
 /**
  * Производит откат исходя из информации сохраненной в директории отката $dir
  *
  * В случае успешного отката возвоащает true, false - в случае если при откате
  * одной из задач было выброшено исключение 
  *
  * @param Dir $dir
  * @return bool
  */
 static function undeploy($dir)
 {
     if (!$dir->exists()) {
         return io::out('Rollback dir(' . $dir . ') not exists.', IO::MESSAGE_WARN) | 2;
     }
     $list = Dir::get($dir, true)->ls('*', Dir::LS_DIR);
     if (count($list) == 0) {
         return io::out('Undeploy list is empty');
     }
     Autoload::addDir(t(new File(__FILE__, true))->getParent()->getDir('deployTasks'));
     $steps = array();
     foreach ($list as $d) {
         $steps[$d->getName()] = array('class' => file_get_contents($d->getFile('.class')), 'dir' => $d);
     }
     krsort($steps);
     foreach ($steps as $s) {
         try {
             call_user_func($s['class'] . '::undeploy', $s['dir']);
         } catch (Exception $e) {
             io::out($e->getMessage(), IO::MESSAGE_FAIL);
             $fail = true;
         }
     }
     return isset($fail) ? false : true;
 }
Exemple #11
0
 /**
  * Создание директорий
  *
  * Создает директрорию(рекрсивно) с маской Dir::MODE.
  * В случае успеха возвращает объект вновь созданной директории Dir.
  *
  * Функция принимает произвольное количество параметров, каждый из которых
  * трактуется как директорию, которую необходимо создать.
  * Если параметров больше чем два функция возвращает массив созданных объектов.
  *
  * В случае если одна из директорий или поддиректорий не создана, функция выбрасывает исключение.
  * 
  * В реализации умышленно не используется параметре $recursive встроенной фукции PHP mkdir().
  *
  * <code>
  *      $dirs = mkdir('non_existent_dir/dir1', 'dir2');
  * </code>
  *
  * Если параметры не указанны, то создается папка $this.
  *
  *
  * @throws FileSystemException
  * @return Dir, Array(Dir) 
  */
 public function mkdir()
 {
     if (($fnc = func_num_args()) == 0) {
         return Dir::get('/', true)->mkdir($this);
     }
     $res = array();
     foreach (func_get_args() as $dir) {
         if (is_null($dir) || empty($dir)) {
             throw new FileSystemException('Directory name is empty or not set.');
         }
         $part = explode('/', $this->concat($dir));
         if (($c = count($part)) > 0) {
             for ($i = 0, $p = $this; $i < $c; $i++) {
                 if (!file_exists($p = $p->getDir($part[$i]))) {
                     if (!mkdir($p, Dir::MODE)) {
                         throw new FileSystemException('Create directory fail. Dir: ' . $p);
                     }
                 }
             }
             $res[] = $this->getDir($dir);
         } else {
             throw new FileSystemException('Incorrect directory name: ' . $dir);
         }
     }
     return $fnc == 1 ? $res[0] : $res;
 }
Exemple #12
0
 /**
  * Trying to retrieve full page path in vendor dir only.
  *
  * @param string partial src of the page to find
  * @return string full path to the page from server's root.
  * @throws ControllerException if unable to find page path
  */
 protected final function vendorPagePath($src)
 {
     $file = Dir::get(Config::get('ROOT_DIR'), true)->getDir(Config::get("vendors_dir"))->getDir('pages')->getFile($src);
     if ($file->exists()) {
         return $file;
     }
     throw new ControllerException('vendor page file ' . $src . ' not found', 1);
 }