Automatically pretty JSON files for clean git commit diffs using git hooks

(This tutorial and others are available in their original format here)

Background
:

Git is a powerful Version Control System that keeps track of differences in files as well as facilitating collaboration between team members. This isn't a git tutorial, but a tutorial to address an annoyance that people face when using git to work collaboratively on an RPG Maker MV project.

Several of the data files in RPG Maker don't save in a nice, pretty format (Systems.json is one in particular).

This causes the git diffs to become cluttered with useless information since all of the text will be on one line, so you can't tell what was actually changed. In addition, the diffs themselves can become large (in terms of bytes).

NonPrettyDiff.png


Pre-requisites:
  • Git is installed on your computer
  • NodeJS is installed on your computer
    • If you're on Windows, install it from the official NodeJS website
    • If you're on Mac, install it with Homebrew. It's so much easier than the official downloadable and it sets the appropriate permissions on your directories

How to do it:

We're going to use a built-in feature of git called "git hooks". There are a variety of hooks available, the one we are going to use is a "pre-commit" hook. This hook runs before the commit action happens.

The hook can execute in basically any language, the default is shell or bash but it's very common to use ruby and python. In this example, we're going to use Javascript.

In order to make use of the pre-commit hook, we need to do the following things:
  1. Identify the JSON files that we want to pretty
  2. Read the file into memory as a string
  3. Parse the string into a Javascript object
  4. Stringify the object back into a string, but with nice line breaks and spacing
  5. Write that string back to the file
  6. Add the file to git tracking again (since it has changed from the hook)
  7. Exit with code 0 if successful, exit with code 1 and print the error if not successful

The code:
Note the code below.

Code:
#!/usr/bin/env node

const files = ['data/System.json']   // add all JSON files here to pretty
const fs = require('fs')
const { exec } = require('child_process')
try {
    files.forEach(file => {
        // Load file, pretty the JSON, and write it back
        const json = fs.readFileSync(`./${file}`)
        fs.writeFileSync(`./${file}`, JSON.stringify(JSON.parse(json), null, 2))
        // Add the file back to the staging since it changed
        exec(`git add ${file}`, (err, stdout, stderr) => {
            if (err) {
                console.error(err)
                process.exit(1)
            }

            console.log(`stdout: ${stdout}`)
            console.log(`stderr: ${stderr}`)
            process.exit(0)
        })
    })

} catch (err) {
    console.error(err)
    process.exit(1)
}

Conclusion:

Save the code above inside your ".git/hooks" folder in your project directory as "pre-commit". So the full path to that file is ".git/hooks/pre-commit" (note: there's no file extension, it's not "pre-commit.js" it's just "pre-commit")

Now this script will run every time files are committed, which will convert the JSON to pretty JSON with spacing and line breaks, so that the differences can be seen in git.

PrettyDiff.png
I'm glad to know I am not the only one who is annoyed with beautifying JSON and some JS files too with RPG maker MV games.

I would, however, like to play the devil's advocate this one time and mention that the read time might be impacted if the file is not minified, as in case of the default Maker functionality.

That being said, I am also frustrated with how "deployment" functions in MV Maker tool and would rather blame minifying on the deployment proces. =)

Thank you for your tutorial.
Yeah, I agree it's frustrating. It's also weird that some files are minified and others aren't, there isn't consistency and not clear exactly why. It's not just deployment either, for example, if you pretty the System.json file then open up the Database inside the editor and close, the file has been minified again. If you have specific gripes about the deployment process, I'd be interested to hear because maybe there's something that can be done outside the editor. That's probably off-topic for this thread though.

I also think the plugins.js file should have been JSON for multiple reasons, one being the ability to split to multiple lines and track changes with git, but that's another topic as well.

Regarding your devil's advocate statement, I really doubt you'll see any performance difference. In Javascript, the JSON.parse function is implemented natively, which means it runs from compiled C++ code, so it's really fast. It also just ignores any whitespace or newline characters so shouldn't affect processing at all. I can't say for sure about the editor itself - we know it's written in Qt (a C++ framework) but we don't know what JSON parsing library they use, hopefully a fast one. I guess I'm an angel's advocate? 😉
First, a big thanks for the inspiration, such hook is so usefull.

The script proposed in this guide can only support a single file being beautified, it can't be expanded to track multiples files.

If we want to beautify more than a single json with this script , it will try to execute a git command while git is already executing, causing a crash (at least it is what I experienced on Windows, I didn't try on another platform)

Solution: adding all beautified files to a git command, then execute it a single time when all work has been done. This version can track the whole /data folder:

Code:
#!/usr/bin/env node

const data_directory = "data"
let command = '';
const fs = require('fs')
const { exec } = require('child_process')
try {
    fs.readdir("data", function (err, files) {
        //handling error
        if (err || files.length <= 0) {
            console.error(err)
            process.exit(1)
        }
     
        files.forEach(file => {
            // Load file, pretty the JSON, and write it back
            const json = fs.readFileSync(`${data_directory}/${file}`)
            fs.writeFileSync(`${data_directory}/${file}`, JSON.stringify(JSON.parse(json), null, 2))
            command += ` ${data_directory}/${file}`
        })
     
        // Add the file back to the staging since it changed
        exec(`git add ${command}`, (err, stdout, stderr) => {
            if (err) {
                console.error(err)
                process.exit(1)
            }

            console.log(`stdout: ${stdout}`)
            console.log(`stderr: ${stderr}`)
            process.exit(0)
        })
     
    });
} catch (err) {
    console.error(err)
    process.exit(1)
}
Hey just wanted to say this is a great solution to the ways that rpgmaker plays badly with git. Ive made a few improvements on the script, namely making the system version id and mapinfo scroll values consistent so that those dont change with every commit and cause annoying conflicts when multiple team members try to merge.
JavaScript:
#!/usr/bin/env node

const data_directory = "data"
let command = '';
const fs = require('fs')
const { exec } = require('child_process');
const { parse } = require('path');
try {
    console.log("Running cleanup...");
    fs.readdir("data", function (err, files) {
        //handling error
        if (err || files.length <= 0) {
            console.error(err)
            process.exit(1)
        }
   
        files.forEach(file => {
            // Load file, pretty the JSON, and write it back
            const json = fs.readFileSync(`${data_directory}/${file}`)
            const parsed = JSON.parse(json);
            // Keep scroll static, this changes every time you view a file
            // and will cause conflicts
            if(file == 'MapInfos.json') {
                parsed.forEach(obj => {
                    if(obj && obj.scrollX) {
                        obj.scrollX = 0
                        obj.scrollY = 0
                    }
                });
            }
            // Keep version static, this changes each time you save a file
            if(file == 'System.json') {
                parsed.versionId = "latest"
            }
            fs.writeFileSync(`${data_directory}/${file}`, JSON.stringify(parsed, null, 2))
            command += ` ${data_directory}/${file}`
        })
   
        // Add the file back to the staging since it changed
        exec(`git add ${command} -f`, (err, stdout, stderr) => {
            if (err) {
                console.error(err)
                process.exit(1)
            }

            console.log(`stdout: ${stdout}`)
            console.log(`stderr: ${stderr}`)
            process.exit(0)
        })
   
    });
} catch (err) {
    console.error(err)
    process.exit(1)
}

Hope this is helpful for other folks who ran into this issue!
Oh wow! It hurts to realize how stupid I was for not searching here when I encountered the issue xD

Ok so obviously, I also have a script that prettifies my JSON data files, no need to share it here, it's very similar to all the others, but maybe one thing that might help is this: on top of that, I took the route of using git hooks (for the first time in my life) to prevent committing minified JSONs:

.git/hooks/pre-commit
Code:
node scripts/check.js

scripts/check.js
JavaScript:
const fs = require('fs');
const { exec } = require('child_process');

function execAsync(command, options) {
  return new Promise((resolve, reject) => {
    exec(command, options, (error, stdout, stderr) => {
      if (error) reject(error);
      else resolve({stdout, stderr});
    });
  });
}

async function main() {
  const { stdout, stderr } = await execAsync('git diff --name-status --staged');
  const files = stdout.split('\n').filter(Boolean).map(f => f.split('\t').pop());
  const jsons = files.filter(f => f.endsWith('.json'));
  const errors = [];
  for (const json of jsons) {
    const content = fs.readFileSync(json, 'utf-8');
    const parsed = JSON.stringify(JSON.parse(content), null, 2);
    if (content !== parsed) {
      errors.push(`File ${json} is not formatted`);
    }
  }
  if (errors.length === 0) {
    console.log('All files well formatted');
    return 0;
  }
  console.log(errors.map(e => `- ${e}`).join('\n'));
  return 1;
}

main().then(code => {
  process.exit(code);
});

Original thread: https://forums.rpgmakerweb.com/threads/automatically-pretty-json-files-for-clean-git-commit-diffs-using-git-hooks.108122/