3.0 / 5

Usar Git Hook pre commit en proyecto Maven Java

1.465K
3

Hola buenas a todos, hoy vamos a ver cómo usar el hook de git “pre-commit”, justo en un proyecto nos quedó unos días libres, y me pidieron investigar un poco sobre los hooks de Git, así que les voy a mostrar dos formas de usar este hook.

Lo que vamos a intentar hacer es lograr que el pre-commit de git ejecute comandos, comandos que usamos en un proyecto Java, como build, test, clean, entro otros.

Vamos a empezar por un proyecto maven base, el pom solo contiene lo siguiente:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.aconcagua.app</groupId>
    <artifactId>githooks</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>githooks</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Luego el proyecto contiene lo siguiente, por ahora solo agregamos la clase principal

 

Vamos a ejecutar el comando “git init” para poder versionar cualquier cambio en nuestro proyecto y de paso tenes los hooks que nos da por defecto.

Ahora vamos a lo más importante, configurar el pre-commit.

 

En la raíz de nuestro proyecto vamos a ver la carpeta oculta “.git” vamos a ingresar a esa carpeta.

 

 

 

Vemos que hay varias carpetas y archivos que usa git para versionar nuestro proyecto, nos vamos a centrar en la carpeta hooks.

 

 

Vemos que hay varios archivos de ejemplo.

 

 

 

 

Lo que vamos a hacer es crear un archivo y lo llamaremos “pre-commit” sin extención. Ahora lo más importante

Le tenemos que dar permisos de ejecución: chmod +x pre-commit

 

Dentro de este archivo vamos a colocar algo como esto:

#!/bin/bash
# save the file as <git_directory>/.git/hooks/pre-commit
echo "Running Maven prettier"
# retrieving current working directory
CWD=`pwd`
MAIN_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# go to main project dir
cd $MAIN_DIR/../../
# running maven clean test
mvn clean test
if [ $? -ne 0 ]; then
  echo "Error while testing the code"
  # go back to current working dir
  cd $CWD
  exit 1
fi
# go back to current working dir
cd $CWD

Si vemos en detalle es un archivo bash común, en donde podremos ejecutar comandos, en este caso comandos de maven.

Vamos a probar ahora si ejecuta el pre-commit cuando hacemos un commit en nuestro repositorio local.

Lo que vamos a hacer es agregar una clase User en el paquete domain:

package com.aconcagua.app.githooks.domain;

import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {

  private static final long serialVersionUID = 1L;
  private Long id;
  private String login;
  private String password;
  private String firstName;
  private String lastName;
  private Long days;
}

Ahora en la consola ejecutamos el comando git status para ver los cambios

Cambios no rastreados para el commit:
  (usa "git add <archivo>..." para actualizar lo que ser'a confirmado)
  (usa "git restore <archivo>..." para descartar los cambios en el directorio de trabajo)
        modificados:     src/main/java/com/aconcagua/app/githooks/domain/User.java

Archivos sin seguimiento:
  (usa "git add <archivo>..." para incluirlo a lo que se ser'a confirmado)
        .DS_Store

Ahora ejecutamos el comando add de git:

git add .

Ejecutamos de nuevo el comando git status y vemos lo siguiente:

En la rama develop
Cambios a ser confirmados:
  (usa "git restore --staged <archivo>..." para sacar del 'area de stage)
        nuevos archivos: .DS_Store
        nuevos archivos: src/main/java/com/aconcagua/app/githooks/domain/User.java

Esto nos indica que está listo para hacer commit al repositorio local. Ahora ejecutamos el siguiente comando:

git commit -am 'Agregamos la clase User.'

Al ejecutar el comando tendremos que ver en la consola la ejecución del pre-commit acorde a lo que configuramos:

git commit -am 'Agregamos la clase User'
Running Maven prettier
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------------< com.aconcagua.app:githooks >---------------------
[INFO] Building githooks 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ githooks ---
[INFO] Deleting /Users/ehgce/IdeaProjects/githooks/target
[INFO] 
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ githooks ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ githooks ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to /Users/ehgce/IdeaProjects/githooks/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ githooks ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory /Users/ehgce/IdeaProjects/githooks/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ githooks ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/ehgce/IdeaProjects/githooks/target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ githooks ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.aconcagua.app.githooks.GithooksApplicationTests
10:19:47.085 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
10:19:47.093 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
10:19:47.120 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.aconcagua.app.githooks.GithooksApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
10:19:47.128 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.aconcagua.app.githooks.GithooksApplicationTests], using SpringBootContextLoader
10:19:47.131 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.aconcagua.app.githooks.GithooksApplicationTests]: class path resource [com/aconcagua/app/githooks/GithooksApplicationTests-context.xml] does not exist
10:19:47.131 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.aconcagua.app.githooks.GithooksApplicationTests]: class path resource [com/aconcagua/app/githooks/GithooksApplicationTestsContext.groovy] does not exist
10:19:47.131 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.aconcagua.app.githooks.GithooksApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
10:19:47.132 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.aconcagua.app.githooks.GithooksApplicationTests]: GithooksApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
10:19:47.161 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.aconcagua.app.githooks.GithooksApplicationTests]
10:19:47.199 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/Users/ehgce/IdeaProjects/githooks/target/classes/com/aconcagua/app/githooks/GithooksApplication.class]
10:19:47.200 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.aconcagua.app.githooks.GithooksApplication for test class com.aconcagua.app.githooks.GithooksApplicationTests
10:19:47.258 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.aconcagua.app.githooks.GithooksApplicationTests]: using defaults.
10:19:47.259 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
10:19:47.265 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
10:19:47.265 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
10:19:47.265 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@42b3b079, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@651aed93, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@4dd6fd0a, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@bb9e6dc, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@5456afaa, org.springframework.test.context.support.DirtiesContextTestExecutionListener@6692b6c6, org.springframework.test.context.event.EventPublishingTestExecutionListener@1cd629b3, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@589da3f3, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@39d76cb5, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@4a00d9cf, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@6736fa8d, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@52815fa3, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@50313382]
10:19:47.267 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@266374ef testClass = GithooksApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@13b3d178 testClass = GithooksApplicationTests, locations = '{}', classes = '{class com.aconcagua.app.githooks.GithooksApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1e66f1f5, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@58a9760d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@49e5f737, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4c309d4d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@548e6d58, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@5649fd9b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
10:19:47.288 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.5)

2021-10-26 10:19:47.446  INFO 77415 --- [           main] c.a.a.githooks.GithooksApplicationTests  : Starting GithooksApplicationTests using Java 16.0.2 on RITM005702315/MAC with PID 77415 (started by ehgce in /Users/ehgce/IdeaProjects/githooks)
2021-10-26 10:19:47.448  INFO 77415 --- [           main] c.a.a.githooks.GithooksApplicationTests  : No active profile set, falling back to default profiles: default
2021-10-26 10:19:48.251  INFO 77415 --- [           main] c.a.a.githooks.GithooksApplicationTests  : Started GithooksApplicationTests in 0.958 seconds (JVM running for 1.553)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.457 s - in com.aconcagua.app.githooks.GithooksApplicationTests
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  16.498 s
[INFO] Finished at: 2021-10-26T10:19:51-03:00
[INFO] ------------------------------------------------------------------------
[develop 0a9c1a0] Agregamos la clase User
 2 files changed, 22 insertions(+)
 create mode 100644 .DS_Store
 create mode 100644 src/main/java/com/aconcagua/app/githooks/domain/User.java

De esta forma verificamos que el hook pre-commit se ejecuta correctamente, y podemos ver que ejecutó correctamente el comando “mvn clean test” y con esto nos da la posibilidad de usar otros comandos que necesitemos en el pre-commit.

Ahora vamos a hacer algunos cambios a nuestro pom.xml para agregar un pluggin prettier, el cual nos va a ayudar a limpiar todo nuestro codigo java.

En el tag “properties” vamos a agregar el goal que va a ejecutar el pluggin prettier.

<properties>
        <java.version>11</java.version>
        <!-- By default just re-write code with prettier -->
        <plugin.prettier.goal>write</plugin.prettier.goal>
    </properties>

Ahora vamos a agregar el plugin “prettier-maven-plugin” dentro del tag “plugins”

<plugin>
                <groupId>com.hubspot.maven.plugins</groupId>
                <artifactId>prettier-maven-plugin</artifactId>
                <version>0.14</version>
                <configuration>
                    <prettierJavaVersion>1.3.0</prettierJavaVersion>
                    <printWidth>120</printWidth>
                    <tabWidth>4</tabWidth>
                    <useTabs>false</useTabs>
                    <ignoreConfigFile>true</ignoreConfigFile>
                    <ignoreEditorConfig>true</ignoreEditorConfig>
                    <!-- Use <inputGlobs> to override the default input patterns -->
                    <inputGlobs>
                        <!-- These are the default patterns, you can omit <inputGlobs> entirely unless you want to override them -->
                        <inputGlob>src/main/java/**/*.java</inputGlob>
                        <inputGlob>src/test/java/**/*.java</inputGlob>
                    </inputGlobs>
                </configuration>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>${plugin.prettier.goal}</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Como podemos ver en esta congfiguracion lo que nos importa a nosotros es lo siguiente:

<printWidth>120</printWidth>
<tabWidth>4</tabWidth>

Lo que va a hacer el plugin con esa configuración es darle un ancho de 120 caracteres a cada línea y una tabulacion de 4 caracteres. Esto depende de cada uno, muchos usan 4 y otros 2 en la cantidad de caracteres de tabulación.

El pom.xml resultante sería el siguiente:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.aconcagua.app</groupId>
    <artifactId>githooks</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>githooks</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
        <!-- By default just re-write code with prettier -->
        <plugin.prettier.goal>write</plugin.prettier.goal>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.hubspot.maven.plugins</groupId>
                <artifactId>prettier-maven-plugin</artifactId>
                <version>0.14</version>
                <configuration>
                    <prettierJavaVersion>1.3.0</prettierJavaVersion>
                    <printWidth>120</printWidth>
                    <tabWidth>4</tabWidth>
                    <useTabs>false</useTabs>
                    <ignoreConfigFile>true</ignoreConfigFile>
                    <ignoreEditorConfig>true</ignoreEditorConfig>
                    <!-- Use <inputGlobs> to override the default input patterns -->
                    <inputGlobs>
                        <!-- These are the default patterns, you can omit <inputGlobs> entirely unless you want to override them -->
                        <inputGlob>src/main/java/**/*.java</inputGlob>
                        <inputGlob>src/test/java/**/*.java</inputGlob>
                    </inputGlobs>
                </configuration>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>${plugin.prettier.goal}</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Ahora en la consola vamos a ejecutar el comando para bajar las dependencias que hagan falta.

mvn clean install

Ahora vamos a modificar el archivo pre-commit y vamos a cambiar la línea

mvn clean test

por

mvn prettier:write && git add -A .

Con estos comandos le estamos indicando al hook que ejecute el comando “prettier:write” para que acomode cada clase que encuentre que no cumpla con las reglas de tabulación y de largo de línea y luego ejecuta “git add -A” para hacer un amend al commit y actualizarlo sin realizar otro commit aparte.

De esta forma lo que queremos lograr es que al hacer commit se limpie y acomode automáticamente todo nuestro código java.

Para ello lo que vamos a hacer en cada clase que tengamos cambiar la tabulación y ponerla de dos para verificar de que se ejecuta el hook y acomoda todo con la tabulación de 4.

public class User implements Serializable {

  private static final long serialVersionUID = 1L;
  private Long id;
  private String login;
  private String password;
  private String firstName;
  private String lastName;
  private Long days;
}
@SpringBootApplication
public class GithooksApplication {

  public static void main(String[] args) {
    SpringApplication.run(GithooksApplication.class, args);
  }

}

En este caso la clase User y GithooksApplication fueron modificamos con tabulacion de 4 a 2 y ahora hacemos commit.

Antes que nada vemos el estado:

 git status
En la rama develop
Cambios no rastreados para el commit:
  (usa "git add <archivo>..." para actualizar lo que ser'a confirmado)
  (usa "git restore <archivo>..." para descartar los cambios en el directorio de trabajo)
        modificados:     pom.xml
        modificados:     src/main/java/com/aconcagua/app/githooks/GithooksApplication.java
        modificados:     src/main/java/com/aconcagua/app/githooks/domain/User.java

sin cambios agregados al commit (usa "git add" y/o "git commit -a")

Vemos que tenemos cambios en el pom.xml y las clases java. Ahora procedemos a hacer commit y veamos si el hook se ejecuta correctamente.

commit -am 'Se agrega dependencia prettier y cambiamos tabulación en clases java.'

Y como vemos a continuación el pre-commit hook se ejecutó correctamente y acomodo las clases java dentro del proyecto:

Running Maven prettier
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------------< com.aconcagua.app:githooks >---------------------
[INFO] Building githooks 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- prettier-maven-plugin:0.14:write (default-cli) @ githooks ---
[INFO] Reformatted file: src/main/java/com/aconcagua/app/githooks/domain/User.java 14ms
[INFO] Reformatted file: src/main/java/com/aconcagua/app/githooks/GithooksApplication.java 6ms
[INFO] Reformatted file: src/test/java/com/aconcagua/app/githooks/GithooksApplicationTests.java 3ms
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  10.485 s
[INFO] Finished at: 2021-10-26T10:55:50-03:00
[INFO] ------------------------------------------------------------------------
[develop 53b3212] Se agrega deendencia prettier y cambiamos tabulacion en clases java.
 3 files changed, 34 insertions(+), 8 deletions(-)

Aparte podemos ver que acomodo la clase de test y las clases que modificamos para que prettier las acomode.

Bueno espero les sea de mucha utilidad para sus proyectos.

Saludos.

 

THIS IS AN OPTIONAL

Related Post

Hola buenas, hoy vamos a ver una pagina bastante interesante para poder compartir con nuestros amigo

3 COMMENTS

LEAVE YOUR COMMENTS