-2

Is there a way in git to do the same thing as 2 shell commands would do:

touch somefile
git add somefile

in one command?

ivan.ukr
  • 2,853
  • 1
  • 23
  • 41

1 Answers1

4

git add copies a file from the work-tree into the index. This process requires that the file exist; git add will use that same name in the index.

Technically, what git add really does consists of two steps:

  1. It must create or find the blob object in the repository database, that contains the contents of the file. If the file is empty, the object that goes into the database, or that is already in the database, has this hash:

    $ git hash-object -t blob --stdin < /dev/null
    e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
    

    You can emulate this by running git hash-object with the -w flag, which tells Git to write the object to the database if needed, then gives you back the hash ID that represents those contents.

  2. Now that the object is in the database (freshly written if needed) and we have its hash ID, git add goes on to update the index. This update consists of deleting any higher stage entries with the same name, and writing to the stage-zero entry. The entry contents are the desired mode of the file—either 100644 if the file should be marked read/write, or 100755 if it should be marked read/write/execute, the stage number (zero), the blob hash ID, and the path (represented as a UTF-8 string).

You can accomplish the second step using git update-info, either with --index-info (which reads from standard input) or --cacheinfo (which is limited to writing stage-zero entries, but that's what you want anyway). For details, see the git update-index documentation.

The problem with doing this instead of touch file; git add file is that unless you already know the hash ID for the contents, and that that hash ID is actually in the Git database already, it still takes two commands: git hash-object -w ... and git update-index .... And in that case, you might as well use the easy commands instead.

(Note that while all repositories have the empty tree, they do not have the empty blob initially.)

torek
  • 448,244
  • 59
  • 642
  • 775