DEV Community

saif ali
saif ali

Posted on • Updated on

Bringing the code format to legacy.

A project without legacy code as hypothetic as the existence of developer who doesn't code.

You might write a clean code today and it will be a legacy code after sometimes, so we can't get rid of the legacy code in our field.

Now let's start the point, we have a project started 2011 and some of the codes are not even changed till date, so i have been assigned to format the entire code base to google style I tried the following bash function to find out the last updated date of each file.

function ghlbt {
         git ls-tree -r --name-only HEAD |
        while read filename  ;
        do
            if
                [[ $filename == *.$1 ]] ; then echo " $filename ," $(git log -1 --format="%ad, %an" -- $filename);
            fi  ;
        done >> $1_$2.csv
}

please replace $1 with the extension and $2 with the directory name or whatever suffix you need

we got a CSV file and order by the date updated.
"%ad, %an" you can change this as well, you can get google for other patterns.

we thought of cleaning up the old one first, but after generating the CSV I realized that we have 1200+ java files and it's not a good idea to format all, so we thought of making use of our Jenkins to do that and make the process automated.

we are using Gradle for building projects. fortunately, there is formatter available for Gradle.

buildscript {
  repositories {
    mavenCentral()
    jcenter {
    }
  }

dependencies {
    classpath "gradle.plugin.com.github.sherter.google-java-format:google-java-format-gradle-plugin:0.8"
  }
}

add the following to plugin
apply plugin: "com.github.sherter.google-java-format"

so the job in Gradle is done now.

in jenkins, we use regular git comments after getting the commit hook to the production branch, and from there we create an intermediate branch, to format the code and commit that to the master after formatting.

Part 2 will be talking about the jenkins pipeline codes.

Top comments (0)