Diferencia entre revisiones de «Git para Administradores»

De MoodleDocs
m (tidy up)
(Actualización de las versiones a 4.4)
 
(No se muestran 32 ediciones intermedias de 2 usuarios)
Línea 1: Línea 1:
{{EnTraduccion}}
{{Frequently updated doc page
{{Instalación}}
|docpagetitle = Git for Administrators
}}
{{Pendiente de traducir}}
{{Instalación de Moodle}}
Esta página describe como mantener una copia de Moodle en su servidor de producción, que pueda ser actualizada fácilmente usando Git. Si Usted tiene personalizaciones del código del núcleo (core) de Moodle, se le recomienda que siga las instrucciones en [https://docs.moodle.org/dev/Quick_Git_start_guide_for_Moodle_development Quick Git start guide for Moodle development]].
Esta página describe como mantener una copia de Moodle en su servidor de producción, que pueda ser actualizada fácilmente usando Git. Si Usted tiene personalizaciones del código del núcleo (core) de Moodle, se le recomienda que siga las instrucciones en [https://docs.moodle.org/dev/Quick_Git_start_guide_for_Moodle_development Quick Git start guide for Moodle development]].


Para obtener el mayor provecho de Git, vale la pena el esfuerzo para entender sus conceptos básicos - vea también la sección inferior. La curva de aprendizaje puede ser difícil, especialmente si Usted está acostumbrado a usar CVS o Subversion.
Para obtener el mayor provecho de Git, vale la pena el esfuerzo para entender sus conceptos básicos - vea también la sección inferior. La curva de aprendizaje puede ser difícil, especialmente si Usted está acostumbrado a usar CVS o Subversion.
== Obtención de Git (Windows, OSX, Linux y otros) ==
== Obtención de Git (Windows, OSX, Linux y otros) ==
El soporte para Git estaba, hasta hace muy poco tiempo, principalmente confinado a Linux, pero actualmente hay archivos para los sistemas operativos más populares:
* Lista de descargas del sitio Git - [http://git-scm.com/download http://git-scm.com/download]
Una vez que haya descargado e instalado el Git relevante para su sistema operativo, las instrucciones (comandos) git de éste documento deberían de trabajar con su sistema operativo.
== Nombres de las ramas de Moodle ==
Las principales versiones de Moodle tienen cada una su propia rama en Git. Por ejemplo, MOODLE_38_STABLE (3.8), MOODLE_404_STABLE (4.4). El desarrollo generalmente se hace en la rama 'master'. Toda la vida de esa versión se conservará en esa rama. Cada versión de Moodle liberada es designada al añadir una etiqueta (tag), como por ejemplo v3.9.0-beta, v3.9.0-rc1, v3.9.0.


El soporte para Git estaba, hasta hace muy poco tiempo, principalmente confinado a Linux, pero actualmente hay archivos para los sitemas operativos más populares:
Desde la versión 4.0, los códigos de versión utilizan 3 dígitos: 400, 401, 402, ...


* Lista de descargas del sitio Git - [http://git-scm.com/download http://git-scm.com/download]
'''Importante''': Aun y cuando el nombre de la rama incluya la palabra STABLE ('ESTABLE') en su nombre, esto no significa que el código en esa rama sea realmente estable. Poco tiempo después de que se haya creado la rama, contendrá versiones 'beta' y RC, o 'release candidate' (candidato-a-liberación), de la nueva versión de Moodle. Es importante revisar que el estado actual de la rama cumpla con las necesidades de usted. Generalmente, la forma más fácil es examinar los contenidos actuales del fichero version.php - substituya la rama en esta URL, https://github.com/moodle/moodle/blob/MOODLE_404_STABLE/version.php
 
Una vez que haya descargado e instalado el Git relevante para su sistema operativo, las instrucciones (comandos) git de éste documento deberían de trabajar con su sistema operativo.


NO USE versiones alfa, beta ni candidatos-a-liberación (alpha, beta, release-candidates o RC) ni tampoco código de la rama maestra (master) para sitios en producción, ya que podrían tener problemas significativos.
== Obtención del código de Git ==
== Obtención del código de Git ==
Aquí se discute la versión de Git para línea de comando. Los clientes gráficos son poco menos que envoltorios alrededor de la versión para línea de comando, por lo que Usted debería de poder deducir los parámetros correctos muy fácilmente.  
Aquí se discute la versión de Git para línea de comando. Los clientes gráficos son poco menos que envoltorios alrededor de la versión para línea de comando, por lo que Usted debería de poder deducir los parámetros correctos muy fácilmente.  


Usted puede encontrar el repositorio Git oficial de Moodle en [git://git.moodle.org/moodle.git git://git.moodle.org/moodle.git] (con una clona oficial en [git://github.com/moodle/moodle.git git://github.com/moodle/moodle.git]). Para inicializar su ''checkout'' local, use
Para inicializar su repositorio local, use los siguientes comandos en el terminal de su servidor:
<pre>
<pre>
$ git clone git://git.moodle.org/moodle.git                       (1)
$ cd /ruta/hacia/su/webroot
$ git clone https://github.com/moodle/moodle.git                 (1)
$ cd moodle
$ cd moodle
$ git branch -a                                                  (2)
$ git branch -a                                                  (2)
$ git branch --track MOODLE_25_STABLE origin/MOODLE_25_STABLE    (3)
$ git branch --track MOODLE_404_STABLE origin/MOODLE_404_STABLE  (3)
$ git checkout MOODLE_25_STABLE                                  (4)
$ git checkout MOODLE_404_STABLE                                  (4)
</pre>El detalle del proceso es el siguiente:
* El comando (1) inicializa el nuevo repositorio local como una copia del repositorio remoto moodle.git desde GitHub. Se recomienda utilizar este repositorio de GitHub ya que es el repositorio público de Moodle, y una copia espejo del utilizado en desarrollo. El repositorio remoto se llama por defecto ''origin''. Este comando creará un nuevo directorio local llamado ''moodle'', en donde se descargan todos los archivos. Esta operación puede tomar un tiempo, porque de hecho está obteniendo toda la historia completa de todas las versiones de Moodle.
 
* El comando (2) lista todas las ramas disponibles. Ahí se puede comprobar si la rama que queremos instalar en el repositorio local existe en el remoto de Moodle
* El comando (3) selecciona la rama local, en este caso MOODLE_404_STABLE, y la configura para que sincronice con la rama MOODLE_404_STABLE del repositorio remoto.
* El comando (4) cambia hacia la rama local recientemente creada. Al finalizar, se puede comprobar la version utilizada en nuestro repositorio local abriendo el archivo version.php
==Clonar utilizando GitHub CLI ==
También se puede utilizar GitHub CLI para clonar el repositorio remoto. Para ello, utilice el siguiente comando en lugar de git clone:
<pre>
$ gh repo clone moodle/moodle
</pre>
</pre>
* El comando (1) inicializa el nuevo repositorio local como una clona del repositorio (ascendente) 'upstream' (basado en el servidor remoto) moodle.git . El repositorio ascendente ''upstream'' se llama por defecto 'origin'. Se crea un nuevo directorio llamado ''moodle'', en donde se descargan todos los archivos. Esta operación puede demorar bastante, porque de hecho está obteniendo toda la historia completa de todas las versiones de Moodle
* El comando (2) enlista todas las ramas disponibles.
* Use el comando (3) para crear una nueva rama local llamada MOODLE_25_STABLE y configurarla para que rastree la rama remota MOODLE_25_STABLE del repositorio ascendente 'upstream'.
* El comando (4) de hecho, cambia hacia la rama local recientemente creada.
Tome nota de que Git tiene muchas opciones para cada comando y que de hecho es posible hacer todo el proceso de arriba con un sólo comando (¡¡¡se les queda de tarea!!!).
==Git desde atrás de un firewall==
Git uses a read-only protocol that may be blocked by your firewall (port 9418). If this is a problem, you can use Github's http version <nowiki>https://github.com/moodle/moodle.git</nowiki>. It's a bit slower, so use the Git protocol if you can.
== Actualización de su instalación ==
== Actualización de su instalación ==
El equipo de desarrolladores de Moodle realiza la integración y prueba de problemas resueltos todos los días Lunes y Martes. En miércoles, Usted puede instalar todos los parches al actualizar su código. Revise la bitácora [http://git.moodle.org/gw?p=moodle.git;a=summary shortlog] para ver si el repositorio oficial ya ha sido actualizado o no.


El equipo de desarrolladores de Moodle realiza la integración y prueba de problemas resueltos los días Lunes y Martes. El miércoles, Usted puede instalar todos los parches al actualizar su código. Revise [http://git.moodle.org/gw?p=moodle.git;a=summary shortlog] para ver si el repositorio oficial ya ha sido actualizado o no.
Para actualizar su código a la versión más reciente (en la rama MOODLE_404_STABLE) '''todo''' lo que tiene que hacer es:
 
Para actualizar su código a la versión más reciente (en la rama MOODLE_25_STABLE) '''todo''' lo que tiene que hacer es:
<pre>
<pre>
$ cd /path/to/your/moodle/
$ cd /ruta/hacia/su/moodle/
$ git pull
$ git pull
</pre>
</pre>
{{Nota| la ruta hacia moodle usualmente es /var/www/html o /var/www/html/moodle en servidores Linux}}
Si éste es un sitio de producción Usted debería de considerar las instrucciones acerca de la [[Actualización_de_moodle]], como por ejemplo, hacer respaldos.
Si éste es un sitio de producción Usted debería de considerar las instrucciones acerca de la [[Actualización_de_moodle]], como por ejemplo, hacer respaldos.
 
== Instalar un plugin opcional desde el repositorio Git ==
== Instalar un complemento desde el repositorio Git ==
{{Pendiente de traducir}}
 
This is one way to handle adding plugins from other Git repositories into your Moodle repository. Another way is to use Git Submodules. However, at the time of writing, this is one of Git's rougher features and should be regarded as an advanced option.  
This is one way to handle adding plugins from other Git repositories into your Moodle repository. Another way is to use Git Submodules. However, at the time of writing, this is one of Git's rougher features and should be regarded as an advanced option.  


FPor ejemplo, digamos que queremos instalar el módulo de [[Libro]] desde su repositorio Git hacia nuestro Moodle 2.5.
For example, let us say we want to install the [[Módulo certificado]] from its Git repository into our Moodle 3.6.
<pre>
<pre>
$ cd /path/to/your/moodle/
$ cd /path/to/your/moodle/
$ cd mod                                                          (1)
$ cd mod                                                          (1)
$ git clone git://github.com/skodak/moodle-mod_book.git book      (2)
$ git clone https://github.com/markn86/moodle-mod_certificate.git certificate    (2)
$ cd book
$ cd certificate
$ git checkout -b MOODLE_25_STABLE origin/MOODLE_25_STABLE       (3)
$ git checkout -b MOODLE_404_STABLE origin/MOODLE_404_STABLE       (3)
$ git branch -d master                                            (4)
$ git branch -d master                                            (4)
</pre>
</pre>
The command (1) changes the current directory into the ''mod'' folder of your local Moodle clone. The command (2) creates a new subdirectory ''book'' and makes a local clone of Petr Škoda's vanilla Book repository. The command (3) creates a new local branch that will track the remote branch with a Book version for Moodle 2.2. The command (4) deletes the ''master'' that was created automatically by git-clone in (2) as we do not want it in this production checkout.
The command (1) changes the current directory into the ''mod'' folder of your local Moodle clone. The command (2) creates a new subdirectory ''certificate'' and makes a local clone of vanilla Certificate repository. The command (3) creates a new local branch that will track the remote branch with a Certificate version for Moodle 3.6. The command (4) deletes the ''master'' that was created automatically by git-clone in (2) as we do not want it in this production checkout.


Note: you should check first the compatibility of a module with your Moodle branch by asking directly to the Maintainer before cloning the repo or - if you want to guess it - by issueing the command below before running the command (3), in order to verify what is available among the branches:
Note: you should check first the compatibility of a module with your Moodle branch by asking directly to the Maintainer before cloning the repo or - if you want to guess it - by issuing the command below before running the command (3), in order to verify what is available among the branches:
<pre>
<pre>
$ git branch -a
$ git branch -a
* master
* master
   remotes/origin/HEAD -> origin/master
   remotes/origin/HEAD -> origin/master
  remotes/origin/MOODLE_15_STABLE
  remotes/origin/MOODLE_17_STABLE
  remotes/origin/MOODLE_18_STABLE
  remotes/origin/MOODLE_19_STABLE
   remotes/origin/MOODLE_20_STABLE
   remotes/origin/MOODLE_20_STABLE
   remotes/origin/MOODLE_21_STABLE
   remotes/origin/MOODLE_21_STABLE
   remotes/origin/MOODLE_22_STABLE
   remotes/origin/MOODLE_22_STABLE
  remotes/origin/MOODLE_23_STABLE
  remotes/origin/MOODLE_24_STABLE
  remotes/origin/MOODLE_25_STABLE
  remotes/origin/MOODLE_26_STABLE
  remotes/origin/MOODLE_27_STABLE
  remotes/origin/MOODLE_28_STABLE
  remotes/origin/MOODLE_29_STABLE
  remotes/origin/MOODLE_30_STABLE
remotes/origin/MOODLE_31_STABLE
   remotes/origin/master
   remotes/origin/master
</pre>
</pre>
This will avoid an error message when you issue the command (3) against a nonexistent branch, e.g.:
This will avoid an error message when you issue the command (3) against a nonexistent branch, e.g.:
<pre>
<pre>
§ git checkout -b MOODLE_25_STABLE origin/MOODLE_25_STABLE
§ git checkout -b MOODLE_31_STABLE origin/MOODLE_31_STABLE
fatal: git checkout: updating paths is incompatible with switching branches.
fatal: git checkout: updating paths is incompatible with switching branches.
Did you intend to checkout 'origin/MOODLE_25_STABLE' which can not be resolved as commit?
Did you intend to checkout 'origin/MOODLE_31_STABLE' which can not be resolved as commit?
</pre>
</pre>
In this case you should ask the Mantainer, here Petr Škoda, if ''master'' is the correct branch for Moodle 2.5+ and he will reply that the [[Book module]] has been already integrated in Moodle starting from 2.3 so there's no need to install it usit ''git''. Please, as a general rule, before asking the Mantainer for something you should check the online documentation.
Note: To fix above error, use: "git fetch origin MOODLE_31_STABLE:LOCAL_MOODLE_31_STABLE"
 
Now it is wise to add the new directory mod/certificate/ to the list of ignored files of the main Moodle clone, otherwise a status of the main clone will keep reminding you that the new code has not been checked in.
Now it is wise to put the new directory mod/book/ to the list of ignored files of the main Moodle clone, otherwise a status of the main clone will keep reminding you that the new code has not been checked in.
<pre>
<pre>
$ cd /path/to/your/moodle/
$ cd /path/to/your/moodle/
$ echo /mod/book/ >> .git/info/exclude
$ echo /mod/certificate/ >> .git/info/exclude
</pre>
</pre>
To update your Moodle installation now, you must visit both Git repositories and pull changes from upstream.
To update your Moodle installation now, you must visit both Git repositories and pull changes from upstream.
Línea 93: Línea 101:
$ cd /path/to/your/moodle/
$ cd /path/to/your/moodle/
$ git pull
$ git pull
$ cd mod/book
$ cd mod/certificate
$ git pull
$ git pull
</pre>
</pre>
Writing a shell script with these lines in the root of Moodle installation is a very good idea. Otherwise it is easy to forget what Git repositories are there within the main Moodle repository.
Writing a shell script with these lines in the root of Moodle installation is a very good idea. Otherwise it is easy to forget what Git repositories are there within the main Moodle repository.
== Installing and maintaining contributed extensions using Git submodules ==
As it was said in the previous section, this is for advanced users only.
Therefore it is necessary, that you have some experience with Git and its commands.
A step-by-step explanation will be provided, but in order to follow these steps it is helpful to understand, what these commands do.
Advanced options and commands can be found at [[https://git-scm.com/book/en/v2/Git-Tools-Submodules|the Git book]].
If you have any questions about Git submodules, please visit the site above first.
=== Installing a new extension into an existing Moodle ===
As an example we use the [[Módulo certificado]] from the previous section.
<pre>
$ cd /path/to/your/moodle
$ git submodule add https://github.com/markn86/moodle-mod_certificate.git mod/certificate
</pre>
Note, that Git is reporting two new files in the repository:
<pre>
$ git status
# On branch MOODLE_29_STABLE
# Changes to be committed:
#  (use "git reset HEAD <file>..." to unstage)
#
# new file:  .gitmodules
# new file:  mod/certificate
#
</pre>
The file '''.gitmodules''' contains the local path and url of all your submodules.
It has to be committed, if you intend to clone the repository later (see the page [https://docs.moodle.org/36/en/Moodle_development_environment_with_Git_submodules development environment with Git submodules]).
Before commiting, make sure to check the configuration of the plugin's Git repository, since the automatically generated settings may be not sufficient.
For future updates it is helpful, to track the remote branch, which corresponds to the Moodle version of your repository.
<pre>
$ cd mod/certificate
$ git branch -avv
* master                          345f5b1 [origin/master] Replaced deprecated function
  remotes/origin/HEAD            -> origin/master
  remotes/origin/MOODLE_20_STABLE 1aa1040 Added option to print 'grade category' grade
  remotes/origin/MOODLE_21_STABLE 1aa1040 Added option to print 'grade category' grade
  remotes/origin/MOODLE_22_STABLE 1aa1040 Added option to print 'grade category' grade
  remotes/origin/MOODLE_23_STABLE fe047de Check that the function exists rather than relying on the Moodle version
  remotes/origin/MOODLE_24_STABLE 1051f7d CONTRIB-4892 Fixed the email to others functionality
  remotes/origin/MOODLE_25_STABLE cdb221a CONTRIB-4946: Removed character from language file breaking AMOS
  remotes/origin/MOODLE_26_STABLE 696802a Increased version
  remotes/origin/MOODLE_27_STABLE d3c0379 Increased version
  remotes/origin/MOODLE_28_STABLE fa8df83 Increased version
  remotes/origin/MOODLE_29_STABLE 3f03740 Replaced deprecated function
  remotes/origin/master          345f5b1 Replaced deprecated function
</pre>
Git created the branch '''master''' which tracks '''origin/master''' automatically, because the remote repository has checked out '''master'''.
Therefore, create a new branch, which tracks the appropriate remote branch.
Of course, this is only possible, if the remote repository offers those branches.
<pre>
$ git checkout -b MOODLE_29_STABLE origin/MOODLE_29_STABLE
Branch MOODLE_29_STABLE set up to track remote branch MOODLE_29_STABLE from origin.
Switched to a new branch 'MOODLE_29_STABLE'
$ git branch -D master
Deleted branch master (was 345f5b1).
</pre>
It is not necessary to delete the '''master''' branch, but it's useless to keep it.
In fact, these settings don't need to be touched afterwards.
The final step is to commit the changes to the main repository.
<pre>
$ cd /path/to/your/moodle
$ git commit -a -m "New extension mod_certificate installed"
</pre>
It has to be ensured, that the commit includes only the changes for the new Git submodule (since '''-a''' commits all non-staged changes).
=== Maintaining Git submodules ===
Maintaining a set of submodules is extremely easy.
Consider a Moodle repository with several submodules installed.
Keep in mind, that the extension '''mod_mylittleextension''' is a fake plugin, created for a test scenario in this example.
It is not an official Moodle module. For updating all your submodules at once, type in:
<pre>
$ cd /path/to/your/moodle
$ git submodule foreach git pull
Entering 'block/coursefeedback'
Already up-to-date.
Entering 'mod/certificate'
Already up-to-date.
Entering 'mod/mylittleextension'
remote: Counting objects: 6, done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
From /local/repositories/mle
  89d9eae..64c122d  master    -> origin/master
Updating 89d9eae..64c122d
Fast-forward
index.html  |    9 +++++++++
version.php |    6 +++---
2 files changed, 12 insertions(+), 3 deletions(-)
create mode 100644 index.html
$ git status
# On branch MOODLE_29_STABLE
# Changes not staged for commit:
#  (use "git add <file>..." to update what will be committed)
#  (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified:  mod/mylittleextension (new commits)
#
</pre>
The command '''git submodule foreach [another command]''' walks through all submodule repositiories and executes what is specified by '''[another command]'''.
In this case it is '''git pull'''.
Therefore the module mylittleextension was updated and the main repository isn't clean anymore until changes are committed:
<pre>
$ git commit -a -m "Plugin updates"
</pre>
Maintaining plugins with Git submodules has also another application than simplifying the update process.
In a greater scale it can be used to maintain a Moodle project, where multiple developers need to have an exact copy of your moodle without organizing external plugins manually.
You can read more about this topic at the page [https://docs.moodle.org/36/en/Moodle_development_environment_with_Git_submodules Moodle development environment with Git submodules].


== Vea también ==
== Vea también ==
; Moodle Docs
; Moodle Docs
* [https://docs.moodle.org/25/en/Git_FAQ Git FAQ]
* [https://docs.moodle.org/36/en/Windows_installation_using_Git Windows installation using Git]
* [https://docs.moodle.org/25/en/Windows_installation_using_Git Windows installation using Git]
* [[Git para Mac]]
* [https://docs.moodle.org/dev/Moodle_versions Moodle versions]
* [https://docs.moodle.org/dev/Moodle_versions Moodle versions]
* For some screenshots see [https://docs.moodle.org/25/en/User:Frank_Ralf/Git User:Frank_Ralf/Git] (still work in progress)
* For fixing a Tracker Issue (MDL) / Forking Moodle / CONTRIButing code ... [https://docs.moodle.org/25/en/User:Sam_Hemelryk/My_Moodle_Git_workflow User:Sam_Hemelryk/My_Moodle_Git_workflow]
* For fixing a Tracker Issue (MDL) / Forking Moodle / CONTRIButing code ... [https://docs.moodle.org/25/en/User:Sam_Hemelryk/My_Moodle_Git_workflow User:Sam_Hemelryk/My_Moodle_Git_workflow]
* [https://docs.moodle.org/25/en/Moodle_Production_Server_with_GIT Case study Git + Moodle from Technical University Berlin]
* [https://docs.moodle.org/36/en/Moodle_Production_Server_with_GIT Case study Git + Moodle from Technical University Berlin]
 
; Documentación Moodle antigua
* [https://docs.moodle.org//en/Git_FAQ Git FAQ]
* For some screenshots see [https://docs.moodle.org/23/en/User:Frank_Ralf/Git User:Frank_Ralf/Git] (still work in progress)
; Moodle forum discussions
; Moodle forum discussions
* [https://moodle.org/mod/forum/discuss.php?d=213695 Got GIT installed on my site- here's how!]
* [https://moodle.org/mod/forum/discuss.php?d=255175 Github and Moodle deployment for production]
* [http://moodle.org/mod/forum/discuss.php?d=168094 GIT help needed]
* [http://moodle.org/mod/forum/discuss.php?d=168094 GIT help needed]
* [http://moodle.org/mod/forum/discuss.php?d=165236 Best way to manage CONTRIB code with GIT]
* [http://moodle.org/mod/forum/discuss.php?d=167063 Handy Git tip for tracking 3rd-party modules and plugins]
* [http://moodle.org/mod/forum/discuss.php?d=167730 Moodle Git repositories]
* [http://moodle.org/mod/forum/discuss.php?d=183693 Git and CVS]
* [http://moodle.org/mod/forum/discuss.php?d=208904 GIT for dummies]
* [http://moodle.org/mod/forum/discuss.php?d=211930 Git and upgrading misunderstanding]
* [https://moodle.org/mod/forum/discuss.php?d=231046 Clear git guide for Admins (not developers)]
* [https://moodle.org/mod/forum/discuss.php?d=231046 Clear git guide for Admins (not developers)]
 
; External resources
; Recursos externos
* [http://thamblings.blogspot.com.au/2013/07/upgrading-moodle-from-git.html Deploying Moodle from git - Blog post from a production experience]
* [http://www.kernel.org/pub/software/scm/git/docs/everyday.html Everyday GIT With 20 Commands Or So]
* [http://gitref.org/ Git Reference]
* [http://gitref.org/ Git Reference]
* [http://progit.org/book/ Pro Git book]
* [http://progit.org/book/ Pro Git book]
* [http://eigenjoy.com/2008/05/15/git-from-the-bottom-up/ Git from the bottom up]
[[Categoría:Git]]
 
[[Categoría:Administrador]]
 
[[https://docs.moodle.org/ja/管理者用Git]]
 
[[https://docs.moodle.org/fr/Git_pour_administrateurs]]
Vea [https://docs.moodle.org/24/en/Git_for_Administrators Git for administrators]
[[https://docs.moodle.org/en/Git for Administrators]]
 
[[Categoría:Git]]
[[ja:管理者用Git]]
[[fr:Git_pour_administrateurs]]
[[en:Git for Administrators]]

Revisión actual - 19:49 22 abr 2024

Nota: Esta es una traducción de una página de la documentación en idioma Inglés (Docs), que se considera particularmente importante, y que en su versión original se actualiza frecuentemente. Por ello, se le recomienda que revise la página original en idioma inglés: Git for Administrators.

Nota: Pendiente de Traducir. ¡Anímese a traducir esta página!.     ( y otras páginas pendientes)

Esta página describe como mantener una copia de Moodle en su servidor de producción, que pueda ser actualizada fácilmente usando Git. Si Usted tiene personalizaciones del código del núcleo (core) de Moodle, se le recomienda que siga las instrucciones en Quick Git start guide for Moodle development].

Para obtener el mayor provecho de Git, vale la pena el esfuerzo para entender sus conceptos básicos - vea también la sección inferior. La curva de aprendizaje puede ser difícil, especialmente si Usted está acostumbrado a usar CVS o Subversion.

Obtención de Git (Windows, OSX, Linux y otros)

El soporte para Git estaba, hasta hace muy poco tiempo, principalmente confinado a Linux, pero actualmente hay archivos para los sistemas operativos más populares:

Una vez que haya descargado e instalado el Git relevante para su sistema operativo, las instrucciones (comandos) git de éste documento deberían de trabajar con su sistema operativo.

Nombres de las ramas de Moodle

Las principales versiones de Moodle tienen cada una su propia rama en Git. Por ejemplo, MOODLE_38_STABLE (3.8), MOODLE_404_STABLE (4.4). El desarrollo generalmente se hace en la rama 'master'. Toda la vida de esa versión se conservará en esa rama. Cada versión de Moodle liberada es designada al añadir una etiqueta (tag), como por ejemplo v3.9.0-beta, v3.9.0-rc1, v3.9.0.

Desde la versión 4.0, los códigos de versión utilizan 3 dígitos: 400, 401, 402, ...

Importante: Aun y cuando el nombre de la rama incluya la palabra STABLE ('ESTABLE') en su nombre, esto no significa que el código en esa rama sea realmente estable. Poco tiempo después de que se haya creado la rama, contendrá versiones 'beta' y RC, o 'release candidate' (candidato-a-liberación), de la nueva versión de Moodle. Es importante revisar que el estado actual de la rama cumpla con las necesidades de usted. Generalmente, la forma más fácil es examinar los contenidos actuales del fichero version.php - substituya la rama en esta URL, https://github.com/moodle/moodle/blob/MOODLE_404_STABLE/version.php

NO USE versiones alfa, beta ni candidatos-a-liberación (alpha, beta, release-candidates o RC) ni tampoco código de la rama maestra (master) para sitios en producción, ya que podrían tener problemas significativos.

Obtención del código de Git

Aquí se discute la versión de Git para línea de comando. Los clientes gráficos son poco menos que envoltorios alrededor de la versión para línea de comando, por lo que Usted debería de poder deducir los parámetros correctos muy fácilmente.

Para inicializar su repositorio local, use los siguientes comandos en el terminal de su servidor:

$ cd /ruta/hacia/su/webroot
$ git clone https://github.com/moodle/moodle.git                  (1)
$ cd moodle
$ git branch -a                                                   (2)
$ git branch --track MOODLE_404_STABLE origin/MOODLE_404_STABLE   (3)
$ git checkout MOODLE_404_STABLE                                  (4)

El detalle del proceso es el siguiente:

  • El comando (1) inicializa el nuevo repositorio local como una copia del repositorio remoto moodle.git desde GitHub. Se recomienda utilizar este repositorio de GitHub ya que es el repositorio público de Moodle, y una copia espejo del utilizado en desarrollo. El repositorio remoto se llama por defecto origin. Este comando creará un nuevo directorio local llamado moodle, en donde se descargan todos los archivos. Esta operación puede tomar un tiempo, porque de hecho está obteniendo toda la historia completa de todas las versiones de Moodle.
  • El comando (2) lista todas las ramas disponibles. Ahí se puede comprobar si la rama que queremos instalar en el repositorio local existe en el remoto de Moodle
  • El comando (3) selecciona la rama local, en este caso MOODLE_404_STABLE, y la configura para que sincronice con la rama MOODLE_404_STABLE del repositorio remoto.
  • El comando (4) cambia hacia la rama local recientemente creada. Al finalizar, se puede comprobar la version utilizada en nuestro repositorio local abriendo el archivo version.php

Clonar utilizando GitHub CLI

También se puede utilizar GitHub CLI para clonar el repositorio remoto. Para ello, utilice el siguiente comando en lugar de git clone:

$ gh repo clone moodle/moodle

Actualización de su instalación

El equipo de desarrolladores de Moodle realiza la integración y prueba de problemas resueltos todos los días Lunes y Martes. En miércoles, Usted puede instalar todos los parches al actualizar su código. Revise la bitácora shortlog para ver si el repositorio oficial ya ha sido actualizado o no.

Para actualizar su código a la versión más reciente (en la rama MOODLE_404_STABLE) todo lo que tiene que hacer es:

$ cd /ruta/hacia/su/moodle/
$ git pull
Nota: la ruta hacia moodle usualmente es /var/www/html o /var/www/html/moodle en servidores Linux


Si éste es un sitio de producción Usted debería de considerar las instrucciones acerca de la Actualización_de_moodle, como por ejemplo, hacer respaldos.

Instalar un plugin opcional desde el repositorio Git

Nota: Pendiente de Traducir. ¡Anímese a traducir esta página!.     ( y otras páginas pendientes)

This is one way to handle adding plugins from other Git repositories into your Moodle repository. Another way is to use Git Submodules. However, at the time of writing, this is one of Git's rougher features and should be regarded as an advanced option.

For example, let us say we want to install the Módulo certificado from its Git repository into our Moodle 3.6.

$ cd /path/to/your/moodle/
$ cd mod                                                          (1)
$ git clone https://github.com/markn86/moodle-mod_certificate.git certificate     (2)
$ cd certificate
$ git checkout -b MOODLE_404_STABLE origin/MOODLE_404_STABLE        (3)
$ git branch -d master                                            (4)

The command (1) changes the current directory into the mod folder of your local Moodle clone. The command (2) creates a new subdirectory certificate and makes a local clone of vanilla Certificate repository. The command (3) creates a new local branch that will track the remote branch with a Certificate version for Moodle 3.6. The command (4) deletes the master that was created automatically by git-clone in (2) as we do not want it in this production checkout.

Note: you should check first the compatibility of a module with your Moodle branch by asking directly to the Maintainer before cloning the repo or - if you want to guess it - by issuing the command below before running the command (3), in order to verify what is available among the branches:

$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/MOODLE_20_STABLE
  remotes/origin/MOODLE_21_STABLE
  remotes/origin/MOODLE_22_STABLE
  remotes/origin/MOODLE_23_STABLE
  remotes/origin/MOODLE_24_STABLE
  remotes/origin/MOODLE_25_STABLE
  remotes/origin/MOODLE_26_STABLE
  remotes/origin/MOODLE_27_STABLE
  remotes/origin/MOODLE_28_STABLE
  remotes/origin/MOODLE_29_STABLE
  remotes/origin/MOODLE_30_STABLE
 remotes/origin/MOODLE_31_STABLE
  remotes/origin/master

This will avoid an error message when you issue the command (3) against a nonexistent branch, e.g.:

§ git checkout -b MOODLE_31_STABLE origin/MOODLE_31_STABLE
fatal: git checkout: updating paths is incompatible with switching branches.
Did you intend to checkout 'origin/MOODLE_31_STABLE' which can not be resolved as commit?
Note: To fix above error, use: "git fetch origin MOODLE_31_STABLE:LOCAL_MOODLE_31_STABLE"

Now it is wise to add the new directory mod/certificate/ to the list of ignored files of the main Moodle clone, otherwise a status of the main clone will keep reminding you that the new code has not been checked in.

$ cd /path/to/your/moodle/
$ echo /mod/certificate/ >> .git/info/exclude

To update your Moodle installation now, you must visit both Git repositories and pull changes from upstream.

$ cd /path/to/your/moodle/
$ git pull
$ cd mod/certificate
$ git pull

Writing a shell script with these lines in the root of Moodle installation is a very good idea. Otherwise it is easy to forget what Git repositories are there within the main Moodle repository.

Installing and maintaining contributed extensions using Git submodules

As it was said in the previous section, this is for advanced users only. Therefore it is necessary, that you have some experience with Git and its commands. A step-by-step explanation will be provided, but in order to follow these steps it is helpful to understand, what these commands do.

Advanced options and commands can be found at [Git book]. If you have any questions about Git submodules, please visit the site above first.

Installing a new extension into an existing Moodle

As an example we use the Módulo certificado from the previous section.

$ cd /path/to/your/moodle
$ git submodule add https://github.com/markn86/moodle-mod_certificate.git mod/certificate

Note, that Git is reporting two new files in the repository:

$ git status
# On branch MOODLE_29_STABLE
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#	new file:   .gitmodules
#	new file:   mod/certificate
#

The file .gitmodules contains the local path and url of all your submodules. It has to be committed, if you intend to clone the repository later (see the page development environment with Git submodules). Before commiting, make sure to check the configuration of the plugin's Git repository, since the automatically generated settings may be not sufficient. For future updates it is helpful, to track the remote branch, which corresponds to the Moodle version of your repository.

$ cd mod/certificate
$ git branch -avv
* master                          345f5b1 [origin/master] Replaced deprecated function
  remotes/origin/HEAD             -> origin/master
  remotes/origin/MOODLE_20_STABLE 1aa1040 Added option to print 'grade category' grade
  remotes/origin/MOODLE_21_STABLE 1aa1040 Added option to print 'grade category' grade
  remotes/origin/MOODLE_22_STABLE 1aa1040 Added option to print 'grade category' grade
  remotes/origin/MOODLE_23_STABLE fe047de Check that the function exists rather than relying on the Moodle version
  remotes/origin/MOODLE_24_STABLE 1051f7d CONTRIB-4892 Fixed the email to others functionality
  remotes/origin/MOODLE_25_STABLE cdb221a CONTRIB-4946: Removed character from language file breaking AMOS
  remotes/origin/MOODLE_26_STABLE 696802a Increased version
  remotes/origin/MOODLE_27_STABLE d3c0379 Increased version
  remotes/origin/MOODLE_28_STABLE fa8df83 Increased version
  remotes/origin/MOODLE_29_STABLE 3f03740 Replaced deprecated function
  remotes/origin/master           345f5b1 Replaced deprecated function

Git created the branch master which tracks origin/master automatically, because the remote repository has checked out master. Therefore, create a new branch, which tracks the appropriate remote branch. Of course, this is only possible, if the remote repository offers those branches.

$ git checkout -b MOODLE_29_STABLE origin/MOODLE_29_STABLE
Branch MOODLE_29_STABLE set up to track remote branch MOODLE_29_STABLE from origin.
Switched to a new branch 'MOODLE_29_STABLE'
$ git branch -D master
Deleted branch master (was 345f5b1).

It is not necessary to delete the master branch, but it's useless to keep it. In fact, these settings don't need to be touched afterwards.

The final step is to commit the changes to the main repository.

$ cd /path/to/your/moodle
$ git commit -a -m "New extension mod_certificate installed"

It has to be ensured, that the commit includes only the changes for the new Git submodule (since -a commits all non-staged changes).

Maintaining Git submodules

Maintaining a set of submodules is extremely easy. Consider a Moodle repository with several submodules installed. Keep in mind, that the extension mod_mylittleextension is a fake plugin, created for a test scenario in this example. It is not an official Moodle module. For updating all your submodules at once, type in:

$ cd /path/to/your/moodle
$ git submodule foreach git pull
Entering 'block/coursefeedback'
Already up-to-date.
Entering 'mod/certificate'
Already up-to-date.
Entering 'mod/mylittleextension'
remote: Counting objects: 6, done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
From /local/repositories/mle
   89d9eae..64c122d  master     -> origin/master
Updating 89d9eae..64c122d
Fast-forward
 index.html  |    9 +++++++++
 version.php |    6 +++---
 2 files changed, 12 insertions(+), 3 deletions(-)
 create mode 100644 index.html
$ git status
# On branch MOODLE_29_STABLE
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#	modified:   mod/mylittleextension (new commits)
#

The command git submodule foreach [another command] walks through all submodule repositiories and executes what is specified by [another command]. In this case it is git pull. Therefore the module mylittleextension was updated and the main repository isn't clean anymore until changes are committed:

$ git commit -a -m "Plugin updates"

Maintaining plugins with Git submodules has also another application than simplifying the update process. In a greater scale it can be used to maintain a Moodle project, where multiple developers need to have an exact copy of your moodle without organizing external plugins manually. You can read more about this topic at the page Moodle development environment with Git submodules.


Vea también

Moodle Docs
Documentación Moodle antigua
Moodle forum discussions
External resources

[[1]] [[2]] [for Administrators]