BeginnerDev
BeginnerDev

Reputation: 97

How to map git log to json?

After run git log --all --pretty=format:"%h%x09%an%x09%ad%x09%s" --date=short --no-merges, my git output looks like below:

84hf6f3 Some Author 2022-07-13 some commit message

the above output is in this order always sha|author|date|commit message.

And here i have a problem, how to map this output to json file, with fields like above?

Thanks for any help!

Upvotes: 0

Views: 589

Answers (2)

axiac
axiac

Reputation: 72376

Using jq:

git log --all --pretty=format:"%h%x09%an%x09%ad%x09%s" --date=short --no-merges | 
  jq -R '[ inputs | split("\t") | { hash: .[0], author: .[1], date: .[2], message: .[3] }]'

The -R (--raw-input) option tells jq that the input is not JSON. Instead, each line of the input is passed to the filter as string.

The jq script (filter) explained

[                     # wrap everything in a list (array)  <---------------------+
  inputs              # process the list of all inputs (a list of strings)       |
  | split("\t")       # each input is split into a list of pieces                |
  | {                 # for each list of pieces created above, create an object  |
      hash: .[0],     # put the first piece as `hash`                      ^     |
      author: .[1],   # the second piece as `author`                       |     |
      date: .[2],     # the third as `date`                                |     |
      message: .[3]   # and so on...                                       |     |
    }                 # this is where the object ends ---------------------+     |
]                     # remember the wrapper on the first line? it ends here ----+

The output looks like:

[
  {
    "hash": "199a8e4a",
    "author": "me",
    "date": "2018-07-05",
    "message": "Implemented frobulator"
  },
  {
    "hash": "85e76d6e",
    "author": "Someone else",
    "date": "2018-07-03",
    "message": "Added a valuable contribution"
  },
  {
    "hash": "ba91c1dc",
    "author": "John Doe",
    "date": "2018-05-24",
    "message": "Initial Commit"
  }
]

Upvotes: 1

Nicky McCurdy
Nicky McCurdy

Reputation: 19573

Using Node.js:

import { simpleGit } from 'simple-git';

simpleGit().log()

Upvotes: 0

Related Questions