elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  Git Update Manager en Batch
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Git Update Manager en Batch  (Leído 4,892 veces)
profinet

Desconectado Desconectado

Mensajes: 30



Ver Perfil
Git Update Manager en Batch
« en: 20 Noviembre 2023, 23:02 pm »

¡Hola comunidad!

Hoy quiero compartir con vosotros un script batch que he creado para simplificar el proceso de actualización de repositorios Git. Este script es especialmente útil si trabajas con varios proyectos y deseas agilizar la tarea de actualizar y sincronizar con un repositorio remoto.

Aquí un resumen de su funcionalidad:

1. Validación de parámetros y dependencias, asegurándose de que Git esté instalado.

2. Configuración de variables, incluyendo rutas de directorios y configuraciones generales.

3. Configuración de banderas para determinar la acción a realizar (actualización o mostrar ayuda).

4. Selección del proyecto a actualizar o mostrar la ayuda según el parámetro proporcionado.

5. Mostrar la ayuda si se solicita mediante el parámetro -h.

6. Actualización del proyecto seleccionado:

    a. Búsqueda del archivo ZIP más reciente en el directorio de proyectos.
    b. Obtención de la fecha y hora actuales para crear un nuevo branch en Git.
    c. Limpieza del directorio de destino, conservando el directorio .git.
    d. Descompresión del último archivo ZIP en el directorio de destino.
    e. Setup de Git y push de cambios al repositorio remoto.

Nota: Este script incluye tres opciones de ejemplo por defecto (-p1, -p2, -p3) para mostrar su funcionalidad. Estas opciones representan proyectos ficticios y repositorios de ejemplo. Estas opciones pueden ser personalizadas o expandidas según las necesidades específicas del usuario. Simplemente modifica las secciones correspondientes del script para reflejar tus proyectos y repositorios reales.

Nota: Este script sigue una aproximación de almacenamiento que guarda copias completas del proyecto con cada commit en lugar de almacenar cambios incrementales (diffs). La elección de almacenar copias completas puede resultar en un mayor uso de espacio en comparación con la técnica tradicional de Git, que almacena solo las diferencias entre commits. Sin embargo, esta estrategia se ha adoptado aquí para simplificar la gestión y garantizar que cada respaldo sea un punto coherente y completamente funcional en el tiempo.

Nota: La gestión de Git en este script puede no seguir las prácticas más ortodoxas, pero está diseñada para simplificar el proceso de realizar backups periódicos de proyectos en la nube. En lugar de utilizar ramas separadas para cada actualización, se utiliza la fecha y hora actual como parte del nombre de la rama, lo que puede no ser la convención típica de Git. La eliminación y recreación del directorio de destino puede ser considerada una aproximación inusual, pero se ha implementado para garantizar una limpieza completa antes de extraer el último respaldo.

En definitiva, este script es una solución práctica para aquellos que buscan una forma rápida y automatizada de mantener respaldos actualizados en un repositorio remoto, aunque puede no seguir las mejores prácticas recomendadas por la comunidad Git.

Código:
@echo off
setlocal enabledelayedexpansion

REM Batch Script for Git Project Update
REM Author: profinet
REM Date: 2023-11-20
REM Version: 0.1

REM Description:
REM This batch script is designed to automate the process of updating Git projects.
REM It includes functionality for handling multiple projects, cleaning the destination directory, extracting the latest backup, and pushing changes to the remote repository.
REM The script is intended to streamline the update process and reduce manual intervention.

REM Author's Note:
REM The script was created by profinet on the specified date. For any inquiries or suggestions, please contact the author.

REM Version History:
REM - Version 0.1 (2023-11-20): Initial release of the script.
REM   This version includes basic functionality for updating Git projects and serves as the foundation for future enhancements.

REM Check for provided input
if "%~1"=="" (
    echo No parameters provided. Exiting...
    exit /b
)

set "validParams=-p1 -p2 -p3 -h"
if "!validParams:%~1=!" equ "%validParams%" (
    echo Invalid parameter: %1
    echo Valid parameters are: %validParams%
    exit /b
)

REM Check for dependencies
set "gitFolder=%ProgramFiles%\Git"
if not exist "%gitFolder%" (
    set "gitFolder=%ProgramFiles(x86)%\Git"
    if not exist "%gitFolder%" (
        echo Git is not installed in the default location. Exiting...
        exit /b
    )
)

REM Create environment variable to use git commands
set "PATH=%PATH%;%gitFolder%\cmd"

REM Set up general variables
set "latestFile="
set "projectDirFrom=C:\Path\To\Your\Projects"
set "projectDirTo=C:\Path\To\Your\Git\Repos"

REM Set up flags
set "updateProject=false"
set "showHelp=false"

REM Read which option was selected
if "%~1" == "-p1" (
    set "updateProject=true"
    set "projectFolder=Project1"
    set "repo_uri=https://git.example.com/your_username/project1.git"
)
if "%~1" == "-p2" (
    set "updateProject=true"
    set "projectFolder=Project2"
    set "repo_uri=https://git.example.com/your_username/project2.git"
)
if "%~1" == "-p3" (
    set "updateProject=true"
    set "projectFolder=Project3"
    set "repo_uri=https://git.example.com/your_username/project3.git"
)
if "%~1" == "-h" set "showHelp=true"

REM Add as many options as needed
:showHelp
if "%showHelp%"=="true" (
    echo Use of script:
    echo   %~nx0 -p1  Update Project1
    echo   %~nx0 -p2  Update Project2
    echo   %~nx0 -p3  Update Project3
    echo   %~nx0 -h   Show help
    exit /b
)

REM Look up the latest backups
if "%updateProject%"=="true" (
    cd "%projectDirFrom%\%projectFolder%\"
    for %%i in (*.zip) do (
        set "currentFile=%%i"
        if "!currentFile!" gtr "!latestFile!" (
            set "latestFile=!currentFile!"
        )
    )

    REM Get date and time to rename the new branch
    set "current_date=!date:/=-!!time::=-!"
    set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
    set dt=%dt: =0%

    if "%updateProject%"=="true" (
        cd /d "%projectDirTo%\%projectFolder%"

        REM Delete all files (excluding .git) in the destination directory
        for %%i in (*) do (
            if /i not "%%i"=="%projectDirTo%\%projectFolder%\.git" (
                del "%%i"
            )
        )

        REM Delete all subdirectories (excluding .git) in the destination directory
        for /d %%i in (*) do (
            if /i not "%%i"=="%projectDirTo%\%projectFolder%\.git" (
                rmdir /s /q "%%i"
            )
        )

        REM Extract the latest zip file to the destination directory
        powershell -command Expand-Archive -Path '%projectDirFrom%\%projectFolder%\!latestFile!' -DestinationPath '%projectDirTo%\%projectFolder%' -Force

        REM Set up Git and push the changes
        git remote add origin %repo_uri%
        git checkout -b %dt%
        cd %projectFolder%
        git add --all
        git commit -m "Update %dt%"
        git push -u origin %dt%
    )
)

echo.
pause > nul
endlocal


En línea

Don't shy away from the terminal; embrace it! In the GNU world, everything is a file.
pyxolo

Desconectado Desconectado

Mensajes: 29


Share your tasks.


Ver Perfil
Re: Git Update Manager en Batch
« Respuesta #1 en: 4 Diciembre 2023, 11:56 am »

Hola,

¡Está bien!

Sin embargo, la parte de configuración de repos la extraería a un fichero .config o .json e implementaría la carga de configuraciones (python + json sería comodísimo).

Por otra parte, el usuario no solo debe configurar los repos si no también cambiar los parámetros permitidos !!! Eso no debería ser así, tu script debería cargar las configuraciones permitidas y así definir los parámetros permitidos, para el usuario debería ser transparente.

Y lo sé, yo algunas veces también pico script personales y los hago así porque solo los voy a usar yo y me simplifica la tarea, solo quería sacarle punta al código JAJAJA.

Un saludo, good work!


En línea

🍀 What's sauce for the goose is sauce for the gander. 🍀
profinet

Desconectado Desconectado

Mensajes: 30



Ver Perfil
Re: Git Update Manager en Batch
« Respuesta #2 en: 21 Diciembre 2023, 19:16 pm »

¡Hola! ¡Agradezco mucho tu comentario!

Estoy de acuerdo en que sería beneficioso hacer el script más flexible, permitiendo la carga de configuración directamente desde un archivo .config. Sin embargo, la razón detrás de su diseño actual fue la intención de involucrar al usuario, brindándole la oportunidad de sumergirse en el código y adaptarlo a sus propias necesidades. Esta aproximación tiene un componente didáctico, ¡y además, puede resultar divertido! :xD

Adicionalmente, parte de la motivación para crear el script de esta manera fue la necesidad de automatizar la gestión de versiones en mi trabajo. Aunque el código puede ser considerado "guarro", encontré satisfacción en su funcionalidad y decidí compartirlo aquí.

Tengo planes de lanzar una actualización con las sugerencias que me has proporcionado. ¡Estoy esperando el momento adecuado, quizás cuando tenga un poco de tiempo libre en el trabajo y nadie esté mirando! En mi ordenador personal, utilizo Parrot OS. :D
En línea

Don't shy away from the terminal; embrace it! In the GNU world, everything is a file.
profinet

Desconectado Desconectado

Mensajes: 30



Ver Perfil
Re: Git Update Manager en Batch
« Respuesta #3 en: 26 Diciembre 2023, 16:58 pm »

¡Hola a todos!

Solo quería informarles de que he actualizado el código de mi script Git Update Manager. La versión 0.2 (publicada el 2023-12-26) ahora incluye manejo de secciones para la configuración de proyectos. Los usuarios pueden editar directamente el archivo de configuración y pasar el nombre del proyecto como parámetro al llamar al script.

* Configuración del fichero gitmgr_config.ini:

     Para cada proyecto, utiliza una sección [NombreProyecto].
     Cierra cada sección con [/NombreProyecto].

    
Código:
    [MiProyecto]
    projectDirFrom=C:\Ruta\Del\Proyecto\Desde
    projectDirTo=C:\Ruta\Del\Proyecto\A
    repo_uri=https://github.com/usuario/proyecto.git
    [/MiProyecto]
    

Ejemplos de Uso:

* Imprimir Nombres de Proyectos:
Código:
gitmgr -f

* Crear Nueva Sección de Proyecto:
Código:
gitmgr -c


* Actualización de un Proyecto Específico:
Código:
gitmgr MiProyecto

Espero que encuentren útil esta actualización y que los ejemplos de uso sean claros. Como siempre, estoy abierto a comentarios y sugerencias.

Código
  1. @echo off
  2. setlocal enabledelayedexpansion
  3.  
  4. set "insideSection="
  5. set "sectionFound="
  6. set "configFile=gitmgr_config.ini"
  7.  
  8. REM Batch Script for Git Project Update
  9. REM Author: profinet
  10. REM Date: 2023-12-26
  11. REM Version: 0.2
  12.  
  13. REM Description:
  14. REM This batch script is designed to automate the process of updating Git projects.
  15. REM It includes functionality for handling multiple projects, cleaning the destination directory,
  16. REM extracting the latest backup, and pushing changes to the remote repository.
  17. REM The script is intended to streamline the update process and reduce manual intervention.
  18.  
  19. REM Author's Note:
  20. REM The script was created by profinet on the specified date. For any inquiries or suggestions, please contact the author.
  21.  
  22. REM Version History:
  23. REM - Version 0.1 (2023-11-20): Initial release of the script.
  24. REM   This version includes basic functionality for updating Git projects and serves as the foundation for future enhancements.
  25.  
  26. REM - Version 0.2 (2023-12-26): Added section handling for project configuration.
  27. REM   Users can now directly edit a configuration file and pass the project name as a parameter when calling the script.
  28.  
  29. REM Call printProjectNames
  30. @if "%1"=="-f" (
  31.    call :printProjectNames
  32.    exit /b
  33. )
  34.  
  35. REM Call createSection
  36. @if "%1"=="-c" (
  37.    call :createSection
  38.    exit /b
  39. )
  40.  
  41. REM Display help section
  42. @if "%1"=="-h" (
  43.    call :displayHelp
  44.    exit /b
  45. )
  46.  
  47. :initCheck
  48. REM Check for provided input
  49. if "%~1"=="" (
  50.    echo ERROR: No parameters provided...
  51.    call :displayHelp
  52.    exit /b
  53. )
  54.  
  55. REM Check for dependencies
  56. set "gitFolder=%ProgramFiles%\Git"
  57. if not exist "%gitFolder%" (
  58.    set "gitFolder=%ProgramFiles(x86)%\Git"
  59.    if not exist "%gitFolder%" (
  60.        echo:
  61.        echo ERROR: Git is not installed in the default location. Exiting...
  62.        call :endPoint
  63.        exit /b
  64.    )
  65. )
  66.  
  67. :configFile
  68. REM Read the configuration from the file
  69. if not exist %configFile% (
  70.    echo:
  71.    echo ERROR: Config file is not found. Exiting...
  72.    call :endPoint
  73.    exit /b
  74. )
  75.  
  76. set "projectSection=%~1"
  77. for /f "tokens=*" %%a in ('type "%configFile%"') do (
  78.    set "line=%%a"
  79.    if "!line!" equ "[%projectSection%]" (
  80.        set "insideSection=1"
  81.        set "sectionFound=1"
  82.    ) else if "!line!" equ "[/!projectSection!]" (
  83.        set "insideSection="
  84.    )
  85.    if defined insideSection (
  86.        REM Extract variables within section
  87.        for /f "tokens=1,* delims==" %%b in ("!line!") do (
  88.            set "varName=%%b"
  89.            set "varValue=%%c"
  90.            set "!varName!=!varValue!"
  91.        )
  92.    )
  93. )
  94.  
  95. REM Check if the section was found
  96. if not defined sectionFound (
  97.    echo:
  98.    echo ERROR: Project section "%projectSection%" not found in the configuration file.
  99.    echo Exiting...
  100.    call :endPoint
  101.    exit /b
  102. )
  103.  
  104. :verifyConfig
  105. REM Display configuration information for user verification
  106. echo:
  107. echo Please verify the configuration information:
  108. echo:
  109. echo   Project: %projectSection%
  110. echo   Project Directory From: !projectDirFrom!
  111. echo   Project Directory To: !projectDirTo!
  112. echo   Repository URI: !repo_uri!
  113. echo:
  114.  
  115. REM Prompt user for confirmation
  116. set /p "confirm=Is the configuration correct? (Y/N): "
  117. if /i "%confirm%" neq "Y" (
  118.    echo:
  119.    echo Exiting...
  120.    call :endPoint
  121.    exit /b
  122. )
  123.  
  124. :doWork
  125. REM Create environment variable to use git commands
  126. set "PATH=%PATH%;%gitFolder%\cmd"
  127.  
  128. REM Look up the latest backups
  129. cd "%projectDirFrom%"
  130. for %%i in (*.zip) do (
  131.    set "currentFile=%%i"
  132.    if "!currentFile!" gtr "!latestFile!" (
  133.        set "latestFile=!currentFile!"
  134.    )
  135. )
  136.  
  137. REM Get date and time to rename the new branch
  138. set "current_date=!date:/=-!!time::=-!"
  139. set "dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%"
  140. set "dt=%dt: =0%"
  141.  
  142. cd /d "%projectDirTo%"
  143.  
  144. REM Delete all files (excluding .git) in the destination directory
  145. for %%i in (*) do (
  146.    if /i not "%%i"=="%projectDirTo%\%projectFolder%\.git" (
  147.        del "%%i"
  148.    )
  149. )
  150.  
  151. REM Delete all subdirectories (excluding .git) in the destination directory
  152. for /d %%i in (*) do (
  153.    if /i not "%%i"=="%projectDirTo%\%projectFolder%\.git" (
  154.        rmdir /s /q "%%i"
  155.    )
  156. )
  157.  
  158. REM Extract the latest zip file to the destination directory
  159. powershell -command Expand-Archive -Path '%projectDirFrom%\!latestFile!' -DestinationPath '%projectDirTo%\' -Force
  160.  
  161. REM Set up Git and push the changes
  162. git remote add origin %repo_uri%
  163. git checkout -b %dt%
  164. cd %projectFolder%
  165. git add --all
  166. git commit -m "Update %dt%"
  167. git push -u origin %dt%
  168.  
  169. call :endPoint
  170. exit /b
  171.  
  172. :printProjectNames
  173. REM Print project names from configuration file
  174. echo:
  175. echo Project Names defined in the configuration file:
  176. echo:
  177. for /f "tokens=1 delims=[]" %%a in ('findstr /r "\[*\]" "%configFile%"') do (
  178.    echo   %%a
  179. )
  180.  
  181. call :endPoint
  182. exit /b
  183.  
  184. :createSection
  185. REM Create a new section in the configuration file
  186. echo:
  187. set /p "newSection=Enter the name of the new project section >> "
  188.  
  189. REM Check if the section already exists
  190. findstr /r "\[%newSection%\]" "%configFile%" >nul
  191. if !errorlevel! equ 0 (
  192.    echo.
  193.    echo ERROR: Project section "%newSection%" already exists in the configuration file.
  194.    echo Exiting...
  195.    exit /b
  196. )
  197.  
  198. REM Prompt user for new project configuration
  199. set /p "projectDirFrom=Enter project directory from >> "
  200. set /p "projectDirTo=Enter project directory to >>  "
  201. set /p "repo_uri=Enter repository URI >> "
  202.  
  203. REM Write the new section to the configuration file
  204. echo:
  205. echo( >>"%configFile%"
  206. echo [%newSection%]>>"%configFile%"
  207. echo projectDirFrom=!projectDirFrom!>>"%configFile%"
  208. echo projectDirTo=!projectDirTo!>>"%configFile%"
  209. echo repo_uri=!repo_uri!>>"%configFile%"
  210. echo [/%newSection%]>>"%configFile%"
  211. echo:
  212. echo New project section "%newSection%" added to the configuration file.
  213. echo:
  214.  
  215. call :endPoint
  216. exit /b
  217.  
  218. :displayHelp
  219. echo:
  220. echo Git Project Update Script - Help
  221. echo:
  222. echo Usage:
  223. echo   project_update.bat [OPTIONS] PROJECT_NAME
  224. echo:
  225. echo Options:
  226. echo   -f         Print project names defined in the configuration file.
  227. echo   -c         Create a new project section in the configuration file.
  228. echo   -h         Display this help section.
  229. echo:
  230. echo Example:
  231. echo   project_update.bat -f
  232. echo   project_update.bat -c
  233. echo   project_update.bat MyProject
  234. echo:
  235. echo For more information, refer to the script documentation.
  236. echo:
  237.  
  238. :endPoint
  239. endlocal
  240. exit /b
  241.  
« Última modificación: 26 Diciembre 2023, 17:00 pm por profinet » En línea

Don't shy away from the terminal; embrace it! In the GNU world, everything is a file.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines