Просмотр исходного кода

Tarea FD3-481 - Comando para el versionado de módulos

gabriel 7 лет назад
Родитель
Сommit
3f11ca761e
6 измененных файлов с 151 добавлено и 20 удалено
  1. 15 0
      README.md
  2. 0 0
      modules.ini
  3. 1 0
      tools/cmd.php
  4. 21 18
      tools/readme.md
  5. 112 0
      tools/src/Command/TagModulesCommand.php
  6. 2 2
      tools/src/ComposerRequireCommand.php

+ 15 - 0
README.md

@@ -13,4 +13,19 @@ Cada vez que se genere un repositorio vendor nuevo, se debe agregar la direcció
 Contiene todos los repositorios que son módulos que se versionan y taguean con el installer.
 Cada vez que se genere un módulo nuevo se debe agregar la dirección del repositorio de bitbucket a este archivo.
 
+#PROCEDIMIENTOS PARA GENERAR BRANCH'S Y TAG'S   
+##Nombres de branch y tag
+    Los branchs y tags se denominaran con vX.Y.Z, siendo la primer letra una "v" para denotar que es una versión, luego X/Y/Z son los números que la identifican.
+    Los branchs solo tendrán las posiciones "X" e "Y".
+    Los tags tendrán las posiciones "X", "Y" y "Z".
+
+##Branch y tag de vendors (este comando esta puesto dentro del .drone.yml)
+    Estos pasos se deben hacer por separado, es decir, primero se debe hacer un branch y luego el tag.
+    Este proceso se hace de forma automática cuando se genera un branch o tag del módulo "installer". Como ejemplo se ponen las lineas de script que ejecuta el drone.
+    NO EJECUTAR ESTAS LINEAS, SON EN FORMA DE EJEMPLO.
+    Primero debemos estar situados en el directorio /opt/flowdat/tools.
+    Para realizar un branch debemos ejecucar la siguiente sentencia
+        php cmd.php make:tag:vendors repositories.ini vX.Y --branch=true
+    Para realizar un tag debemos ejecucar la siguiente sentencia
+        php cmd.php make:tag:vendors repositories.ini vX.Y.Z
 

tools/modules.ini → modules.ini


+ 1 - 0
tools/cmd.php

@@ -20,5 +20,6 @@ $app->add(new FD3\Command\MakeSubversionCommand());
 $app->add(new FD3\ImportClient());
 $app->add(new FD3\Command\ImportONUCommand());
 $app->add(new FD3\Command\TagVendorsCommand());
+$app->add(new FD3\Command\TagModulesCommand());
 
 $app->run();

+ 21 - 18
tools/readme.md

@@ -164,25 +164,28 @@
         exit
     Ejecuto nuevamente el playbook (ansible)
 
-   
-#Nombres de branch y tag
-    Los branchs y tags se denominaran con vX.Y.Z, siendo la primer letra una "v" para denotar que es una versión, luego X/Y/Z son los números que la identifican.
-    Los branchs solo tendrán las posiciones "X" e "Y".
-    Los tags tendrán las posiciones "X", "Y" y "Z".
-
-#Branch y tag de vendors
-    Estos pasos se deben hacer por separado, es decir, primero se debe hacer un branch y luego el tag.
-    Primero debemos estar situados en el directorio /opt/flowdat/tools.
-    Para realizar un branch debemos ejecucar la siguiente sentencia
-        php cmd.php make:tag:vendors repositories.ini vX.Y --branch=true
-    Para realizar un tag debemos ejecucar la siguiente sentencia
-        php cmd.php make:tag:vendors repositories.ini vX.Y.Z 
 
-#Branch y tag de módulos
+
+#PROCEDIMIENTOS PARA GENERAR BRANCH'S Y TAG'S   
+##Branch y tag de módulos
+    Cuando me conecto al servidor, debo conectarme con un ssh -A ... para pasarle mis credenciales actuales.
     Primero debemos estar situados en el directorio /opt/flowdat/tools.
     Ahora debemos modificar los archivos "composer.json" de cada módulo y ajustarlo a la versión deseada. Este proceso ejecuta el composer update, por lo tanto se debe tener en cuenta que se debe ejecutar en alguna máquina que posea los dockers de los módulos creados.
-    Para esto debemos ejecutar la siguiente sentencia
-        php cmd.php composer:require modules.ini ik/* vX.Y.Z --composer_update=true --pull=master
-    Una vez finalizado la generación de los composer json/lock, debemos hacer un commit de los cambios y para esto ejecutamos la sentencia
-        php cmd.php make:tag:vendors modules.ini vX.Y.Z
+    Si no poseo instalado php (es mejor ejecutarlo de esta forma por el tema de permisos):
+        Nos situamos en el directorio
+            cd /opt/flowdat
+        Ejecuto el dind pasando mis credenciales actuales al docker. Tomar como precaución, que debo tener cargada la de bitbucket de escritura
+            docker run -it -v $(pwd):$(pwd) -v /var/run/docker.sock:/tmp/docker.sock -v "$SSH_AUTH_SOCK:/tmp/ssh_auth_sock" -e "SSH_AUTH_SOCK=/tmp/ssh_auth_sock" dind bash
+        Como el dind carga las variables por el entrypoint, entoces tengo que ejecuar un export para que me tome las keys de la maquina origen
+            export SSH_AUTH_SOCK=/tmp/ssh_auth_sock
+        Ejecuto la sentencia para cambiar el composer y actualizar el fuente
+            php cmd.php composer:require ../modules.ini ik/* vX.Y.Z --composer_update=true --merge=master
+        Una vez finalizado la generación de los composer json/lock, debemos hacer un commit de los cambios y para esto ejecutamos la sentencia
+            php cmd.php make:tag:modules ../modules.ini vX.Y.Z    
         
+    Si poseo instalado php:
+        Para esto debemos ejecutar la siguiente sentencia
+            php cmd.php composer:require ../modules.ini ik/* vX.Y.Z --composer_update=true --merge=master
+        Una vez finalizado la generación de los composer json/lock, debemos hacer un commit de los cambios y para esto ejecutamos la sentencia
+            php cmd.php make:tag:vendors ../modules.ini vX.Y.Z
+

+ 112 - 0
tools/src/Command/TagModulesCommand.php

@@ -0,0 +1,112 @@
+<?php
+
+namespace FD3\Command;
+
+use Symfony\Component\Console\Command\Command;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Input\InputArgument;
+use Symfony\Component\Console\Input\InputOption;
+use Symfony\Component\Console\Output\OutputInterface;
+
+use PHPGit\Git;
+use PHPGit\Exception\GitException;
+
+use WriteiniFile\WriteiniFile;
+
+class TagModulesCommand extends Command
+{
+    protected function configure()
+    {
+        $this
+            ->setName('make:tag:modules')
+            ->setDescription('Tags all vendor from bitbucket')
+            ->setHelp('Tag all vendors from bitbucket')
+            ->addArgument('ini_file', InputArgument::REQUIRED,
+                'The ini file from where to get the source code config.')
+            ->addArgument('tag', InputArgument::REQUIRED, 'Create tag e.g. vX.Y.Z and branch X.Y')
+            ->addOption('remote_git', null, InputOption::VALUE_OPTIONAL,
+                'Indicates the remote for git', 'origin');
+    }
+
+    protected function execute(InputInterface $input, OutputInterface $output)
+    {
+        $file = $input->getArgument("ini_file");
+        $tag = $input->getArgument("tag");
+	$optionRemoteGit = $input->getOption('remote_git');
+        if (strtolower(substr($tag, 0, 1)) == 'v') {
+            $version = explode(".", $tag);
+            if (count($version) == 3) {
+                unset($version[count($version) - 1]);
+            }
+            $version = implode(".", $version);
+
+            $realpath = realpath($file);
+            $dirname = dirname($realpath);
+            if (!chdir($dirname)) {
+                throw new \Exception("Can't change working directory to " . $dirname);
+            }
+
+            $content = parse_ini_file($realpath, true);
+            foreach ($content as $sec => $conf) {
+                $output->writeln("----------------------------------------------------------------------");
+                $output->writeln($sec);
+                $content[$sec]["branch"] = $version;
+                try {
+                    $git = new Git();
+                    $git_path = $dirname . '/' . $sec;
+		    $cd_path = "cd " . $git_path;
+                    // agrego datos del usuario
+                    $git->config->add('user.email', 'drone@flowdat.com', ["global" => true]);
+                    $git->config->add('user.name', 'drone', ["global" => true]);
+                    // agrego el path del repositorio
+		    $git->setRepository($git_path);
+		    // guardo cualquier cambio realizado.
+		    //$git->stash();
+                    // necesito traer todos los branch's para ver si ya existe
+                    $branchs = $git->branch(['all' => true]);
+                    $findBranch = false;
+                    $branchRemote = null;
+                    // verifico si el branch a crear ya existe
+		    foreach ($branchs as $branch) {
+                        if ($branch['name'] == $version) {
+                            $findBranch = true;
+                            $branchRemote = $branch['name'];
+                            break;
+                        }
+                    }
+                    if (!$findBranch) {
+                        // si no existe el branch y estoy creando un branch nuevo
+                        $git->branch->create($version);
+                    }
+		    // cambio a la rama de la version y agrego los archivos modificados
+                    $git->checkout($version);
+                    $git->add('composer.json');
+                    $git->add('composer.lock');
+
+                    shell_exec($cd_path . "; git commit -am 'Composer para la version " . $version . " y el tag " . $tag . "'");
+                    shell_exec($cd_path . "; git push " . $optionRemoteGit . " " . $version );
+                    // estoy creando un tag
+                    $tags = $git->tag();
+                    if (!in_array($tag, $tags)) {
+                        // el tag no existe
+                        if ($branchRemote == null) {
+                            // el branch remote no existe
+                            $git->tag->create($tag, $version);
+                        } else {
+                            // utilizo el branch remoto
+                            $git->tag->create($tag, $branchRemote);
+                        }
+                    }
+                    // ejecuto el comando git
+                    shell_exec($cd_path . "; git push " . $optionRemoteGit . " --tags ");
+                } catch (GitException $e) {
+                    $output->writeln("SE PRODUJO UN ERROR EN " . $sec);
+                    $output->writeln($e->getTraceAsString());
+                    $output->writeln($sec . ": " . $e->getMessage());
+                    return $e->getCode();
+                }
+            }
+        }
+        return 0;
+    }
+}

+ 2 - 2
tools/src/ComposerRequireCommand.php

@@ -44,7 +44,7 @@ class ComposerRequireCommand extends Command
                 $composer_data = json_decode(file_get_contents($composer_file), true);
                 foreach (array("require", "require-dev") as $k) {
 		    if (strlen($pull) > 0) {
-                        shell_exec('cd ' . $sec . '; git pull origin ' . $pull);
+                        shell_exec('cd ' . $sec . '; git checkout master; git pull origin ' . $pull);
                     }
                     foreach ($composer_data[$k] as $package => $version) {
                         if (strpos($packages, "*") !== false) {
@@ -63,7 +63,7 @@ class ComposerRequireCommand extends Command
                 }
                 file_put_contents($composer_file, json_encode($composer_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
 		if ($dockerCompose) {
-                    shell_exec('docker-compose run ' . $sec . ' bin/composer-update.sh');
+                    shell_exec('docker-compose exec ' . $sec . ' bin/composer-update.sh');
                 }
             } else {
                 $output->writeln($sec . " no composer.json found");