0

I want to print the latest commit hash in my Node.js application.

I found a similar discussion here, but it's not what I have in mind. I want to read this information from within Node.js, without running git commands in a terminal.

So if possible, I want to read the .git folder with fs, find the latest commit hash and write it to a variable. This file looks relevant: .git/logs/refs/heads/master.

Can I simply read the last non-empty line of this file and parse the commit hash from there? Any pitfalls I should look for? Any better ways? It's safe to assume I have only one branch (master)

Thanks for any help!

wololoo
  • 147
  • 1
  • 1
  • 9
  • Do you want the currently checked out commit or the latest commit of a specific branch (such as master)? Because the path you mention does the later. In other words: do you want `git rev-parse HEAD` or `git rev-parse master`? – Joachim Sauer Jan 27 '23 at 09:04
  • Don't know really, not that proficient with git. But I want to do it from within Node.js, not a terminal. – wololoo Jan 28 '23 at 03:51

1 Answers1

2

To get the hash for the current (pointed to by the HEAD) commit:

git rev-parse HEAD

To get the hash for the last commit on master branch (in case you moved HEAD to a different commit using git checkout or git switch):

git rev-parse master
phd
  • 82,685
  • 13
  • 120
  • 165
  • 1
    If I read OP correctly they want to do it without a `git` command call. – Joachim Sauer Jan 27 '23 at 09:05
  • 1
    @JoachimSauer Using `git` commands is the only correct way. Reading files in `.git/` subdirectory is like reading binary SQL dumps instead of using a proper client and SQL commands. Unnecessary and fragile (the structure is private, it belongs to Git and is subject to change at any moment). – phd Jan 27 '23 at 09:55
  • Yes but I want my node application to read the commit and print it inside an HTML file or something. Maybe a node library for that? – wololoo Jan 28 '23 at 03:51
  • 1
    @wololoo That information should be in the question and in the tags. – phd Jan 28 '23 at 03:59
  • 1
    I wanted to keep it not specific to Node so maybe people from other platforms can use the information. But you are right, I emphasized this more specifically in the question now. – wololoo Jan 28 '23 at 04:06
  • 1
    @phd I agree and want to emphasize that using `git` directly (or using a library as libgit2) is the only reliable approach. For instance the assumption "I want to read the .git folder" fails spectacularly for [worktrees](https://git-scm.com/docs/git-worktree) where `.git` is a file instead. – hlovdal Jan 28 '23 at 11:01