Git
Português (Brasil) ▾Topics ▾Latest version ▾ git-update-index last updated in 2.43.0

NOME

git-update-index - Registra o conteúdo do arquivo no índice da árvore de trabalho

RESUMO

git update-index
	     [--add] [--remove | --force-remove] [--replace]
	     [--refresh] [-q] [--unmerged] [--ignore-missing]
	     [(--cacheinfo <modo>,<objeto>,<arquivo>)…​]
	     [--chmod=(+|-)x]
	     [--[no-]assume-unchanged]
	     [--[no-]skip-worktree]
	     [--[no-]ignore-skip-worktree-entries]
	     [--[no-]fsmonitor-valid]
	     [--ignore-submodules]
	     [--[no-]split-index]
	     [--[no-|test-|force-]untracked-cache]
	     [--[no-]fsmonitor]
	     [--really-refresh] [--unresolve] [--again | -g]
	     [--info-only] [--index-info]
	     [-z] [--stdin] [--index-version <n>]
	     [--verbose]
	     [--] [<arquivo>…​]

DESCRIÇÃO

Modifica o índice. Cada arquivo mencionado é atualizado no índice e em qualquer estado não mesclado ou que precise ser atualizado será limpo.

Consulte também git-add[1] para conhecer uma maneira mais amigável ao usuário de executar algumas das operações mais comuns no índice.

A maneira como o git update-index trata os arquivos mencionados pode ser alterada utilizando as várias opções:

OPÇÕES

--add

If a specified file isn’t in the index already then it’s added. Default behaviour is to ignore new files.

--remove

If a specified file is in the index but is missing then it’s removed. Default behavior is to ignore removed files.

--refresh

Examina o índice atual e verifica se as mesclagens são necessárias ou atualizações, verificando as informações do stat().

-q

Quiet. If --refresh finds that the index needs an update, the default behavior is to error out. This option makes git update-index continue anyway.

--ignore-submodules

Do not try to update submodules. This option is only respected when passed before --refresh.

--unmerged

If --refresh finds unmerged changes in the index, the default behavior is to error out. This option makes git update-index continue anyway.

--ignore-missing

Ignora os arquivos ausentes durante um --refresh

--cacheinfo <modo>,<objeto>,<caminho>
--cacheinfo <modo> <objeto> <caminho>

Directly insert the specified info into the index. For backward compatibility, you can also give these three arguments as three separate parameters, but new users are encouraged to use a single-parameter form.

--index-info

Leia a informação do índice a partir do stdin.

--chmod=(+|-)x

Defina as permissões de execução nos arquivos atualizados.

--[no-]assume-unchanged

When this flag is specified, the object names recorded for the paths are not updated. Instead, this option sets/unsets the "assume unchanged" bit for the paths. When the "assume unchanged" bit is on, the user promises not to change the file and allows Git to assume that the working tree file matches what is recorded in the index. If you want to change the working tree file, you need to unset the bit to tell Git. This is sometimes helpful when working with a big project on a filesystem that has a very slow lstat(2) system call (e.g. cifs).

O Git falhará (de forma elegante) caso precise modificar este arquivo no índice, quando for mesclar em um commit por exemplo; portanto, caso o arquivo assumido não monitorado seja alterado na upstream, você precisará lidar com a situação de forma manual.

--really-refresh

Como a opção --refresh, porém verifica as informações das estatísticas incondicionalmente, sem considerar a configuração "assuma como inalterado".

--[no-]skip-worktree

Quando uma destas opções é utilizada, os nomes dos objetos registrados nos caminhos não são atualizados. Em vez disso, estas opções definem e desabilitam o bit "skip-worktree" (ignore a árvore de trabalho) dos caminhos. Para mais informações, consulte a seção "Skip-worktree bit" abaixo.

--[no-]ignore-skip-worktree-entries

Não remova o skip-worktree (também informado como "index-only"), mesmo quando a opção --remove for utilizada.

--[no-]fsmonitor-valid

Quando uma destas opções é utilizada, os nomes dos objetos registrados nos caminhos não são atualizados. Em vez disso, essas opções definem e desabilitam o bit "fsmonitor valid" (fsmonitor válido) para os caminhos. Para mais informações, consulte a seção "Monitor do Sistema de Arquivos" abaixo.

-g
--again

Executa o próprio comando git update-index nos caminhos cujas entradas do índice sejam diferentes daquelas do commit HEAD.

--unresolve

Restaura a condição unmerged (não mesclado) ou needs updating (precisa ser atualizado) de um arquivo, durante uma mesclagem caso ele tenha sudo eliminado por engano.

--info-only

Não crie os objetos no banco de dados dos objetos para todos os argumentos <arquivo> que seguem esta opção; basta inserir os seus IDs do objeto no índice.

--force-remove

Remova o arquivo do índice, mesmo quando o diretório ativo ainda tenha tal arquivo. (Implica no uso da opção --remove.)

--replace

By default, when a file path exists in the index, git update-index refuses an attempt to add path/file. Similarly if a file path/file exists, a file path cannot be added. With --replace flag, existing entries that conflict with the entry being added are automatically removed with warning messages.

--stdin

Instead of taking a list of paths from the command line, read a list of paths from the standard input. Paths are separated by LF (i.e. one path per line) by default.

--verbose

Relate o que está sendo adicionado e removido do índice.

--index-version <n>

Write the resulting index out in the named on-disk format version. Supported versions are 2, 3, and 4. The current default version is 2 or 3, depending on whether extra features are used, such as git add -N. With --verbose, also report the version the index file uses before and after this command.

Version 4 performs a simple pathname compression that reduces index size by 30%-50% on large repositories, which results in faster load time. Git supports it since version 1.8.0, released in October 2012, and support for it was added to libgit2 in 2016 and to JGit in 2020. Older versions of this manual page called it "relatively young", but it should be considered mature technology these days.

--show-index-version

Report the index format version used by the on-disk index file. See --index-version above.

-z

Só faz algum sentido se for utilizado com --stdin or --index-info; os caminhos são separados com caracteres NUL em vez de LF.

--split-index
--no-split-index

Ativar ou desativar o modo com o índice dividido. Se o modo com índice dividido já estiver ativado e a opção --split-index for utilizada novamente, todas as alterações no $GIT_DIR/index serão retornadas ao arquivo do índice compartilhado.

Estas opções entram em vigor independente de quer configuração da variável existente no core.splitIndex (consulte git-config[1]). Porém um aviso é emitido quando a alteração vai contra o valor configurado pois o valor configurado apenas entrará em vigor na próxima vez que o índice for lido, removendo o efeito pretendido da opção.

--untracked-cache
--no-untracked-cache

Ative ou desative o recurso de cache não rastreado. Antes de ativar utilize --test-untracked-cache.

Estas opções entram em vigor independente de quer configuração da variável existente no core.untrackedCache (consulte git-config[1]). Porém um aviso é emitido quando a alteração vai contra o valor configurado pois o valor configurado apenas entrará em vigor na próxima vez que o índice for lido, removendo o efeito pretendido da opção.

--test-untracked-cache

Execute apenas os testes no diretório ativo para garantir que o cache não monitorado possa ser utilizado. Você deve habilitar manualmente o cache não monitorado utilizando a opção --untracked-cache ou --force-untracked-cache ou a variável de configuração core.untrackedCache posteriormente, caso realmente queira utilizá-lo. Caso um teste falhe, o código de encerramento gerado é 1 e uma mensagem explica o que não está funcionando, conforme necessário, caso contrário, o código de encerramento é 0 e um OK é impresso.

--force-untracked-cache

O mesmo que --untracked-cache. Fornece compatibilidade retroativa com as versões mais antigas do Git, onde --untracked-cache costumava implicar com a opção --test-untracked-cache, porém esta opção ativaria a extensão incondicionalmente.

--fsmonitor
--no-fsmonitor

Ativar ou desativar o recurso de monitoramento do sistema de arquivos. Estas opções entram em vigor independente de quer configuração da variável existente no core.fsmonitor (consulte git-config[1]). Porém um aviso é emitido quando a alteração vai contra o valor configurado pois o valor configurado apenas entrará em vigor na próxima vez que o índice for lido, removendo o efeito pretendido da opção.

--

Não interprete mais argumentos como opções.

<arquivo>

Files to act on. Note that files beginning with . are discarded. This includes ./file and dir/./file. If you don’t want this, then use cleaner names. The same applies to directories ending / and paths with //

USANDO A OPÇÃO --REFRESH

A opção --refresh não calcula um novo arquivo sha1 ou atualiza o índice para as alterações do modo/conteúdo. Porém o que é feito é "repetir a coincidência" das informações estatísticas de um arquivo ao índice, para que você possa atualizar o índice de um arquivo que não foi alterado, porém onde a entrada da estatísticas esteja desatualizada.

Como por exemplo, você gostaria de fazer isso após fazer um comando git read-tree, para vincular os detalhes do índice estatístico aos arquivos adequados.

USANDO AS OPÇÕES --CACHEINFO OU --INFO-ONLY

--cacheinfo is used to register a file that is not in the current working directory. This is useful for minimum-checkout merging.

Para fingir que você tem um arquivo no caminho com modo e o sha1, use:

$ git update-index --add --cacheinfo <modo>,<sha1>,<caminho>

--info-only is used to register files without placing them in the object database. This is useful for status-only repositories.

Both --cacheinfo and --info-only behave similarly: the index is updated but the object database isn’t. --cacheinfo is useful when the object is in the database but the file isn’t available locally. --info-only is useful when the file is available, but you do not wish to update the object database.

USANDO A OPÇÃO --INDEX-INFO

--index-info is a more powerful mechanism that lets you feed multiple entry definitions from the standard input, and designed specifically for scripts. It can take inputs of three formats:

  1. mode SP type SP sha1 TAB path

    Este formato serve para colocar a saída git ls-tree no índice.

  2. mode SP sha1 SP stage TAB path

    Este formato serve para colocar os estágios na ordem superior do arquivo no índice e coincide à saída do git ls-files --stage.

  3. mode SP sha1 TAB path

    Este formato não é mais gerado por nenhum comando Git, mas é e continuará sendo compatível através do comando update-index --index-info.

Para colocar um estágio de lançamento com prioridade mais alta ao índice, o caminho primeiro deve ser removido ao utilizar mode=0 para o caminho e em seguida alimentando as linhas necessárias da entrada ao terceiro formato.

Como por exemplo, começando com este índice:

$ git ls-files -s
100644 8a1218a1024a212bb3db30becd860315f9f3ac52 0       frotz

você pode alimentar a seguinte entrada para --index-info:

$ git update-index --index-info
0 0000000000000000000000000000000000000000	frotz
100644 8a1218a1024a212bb3db30becd860315f9f3ac52 1	frotz
100755 8a1218a1024a212bb3db30becd860315f9f3ac52 2	frotz

The first line of the input feeds 0 as the mode to remove the path; the SHA-1 does not matter as long as it is well formatted. Then the second and third line feeds stage 1 and stage 2 entries for that path. After the above, we would end up with this:

$ git ls-files -s
100644 8a1218a1024a212bb3db30becd860315f9f3ac52 1	frotz
100755 8a1218a1024a212bb3db30becd860315f9f3ac52 2	frotz

UTILIZANDO O BIT “ASSUME UNCHANGED”

Many operations in Git depend on your filesystem to have an efficient lstat(2) implementation, so that st_mtime information for working tree files can be cheaply checked to see if the file contents have changed from the version recorded in the index file. Unfortunately, some filesystems have inefficient lstat(2). If your filesystem is one of them, you can set "assume unchanged" bit to paths you have not changed to cause Git not to do this check. Note that setting this bit on a path does not mean Git will check the contents of the file to see if it has changed — it makes Git to omit any checking and assume it has not changed. When you make changes to working tree files, you have to explicitly tell Git about it by dropping "assume unchanged" bit, either before or after you modify them.

In order to set "assume unchanged" bit, use --assume-unchanged option. To unset, use --no-assume-unchanged. To see which files have the "assume unchanged" bit set, use git ls-files -v (see git-ls-files[1]).

The command looks at core.ignorestat configuration variable. When this is true, paths updated with git update-index paths... and paths updated with other Git commands that update both index and working tree (e.g. git apply --index, git checkout-index -u, and git read-tree -u) are automatically marked as "assume unchanged". Note that "assume unchanged" bit is not set if git update-index --refresh finds the working tree file matches the index (use git update-index --really-refresh if you want to mark them as "assume unchanged").

Sometimes users confuse the assume-unchanged bit with the skip-worktree bit. See the final paragraph in the "Skip-worktree bit" section below for an explanation of the differences.

EXEMPLOS

Para atualizar e renovar apenas os arquivos já averiguados:

$ git checkout-index -n -f -a && git update-index --ignore-missing --refresh
Em um sistema de arquivos ineficiente com o a opção da configuração core.ignorestat definida
$ git update-index --really-refresh              (1)
$ git update-index --no-assume-unchanged foo.c   (2)
$ git diff --name-only                           (3)
$ edit foo.c
$ git diff --name-only                           (4)
M foo.c
$ git update-index foo.c                         (5)
$ git diff --name-only                           (6)
$ edit foo.c
$ git diff --name-only                           (7)
$ git update-index --no-assume-unchanged foo.c   (8)
$ git diff --name-only                           (9)
M foo.c
  1. impõem ao lstat(2) que defina os bits "assuma como inalterado" para os caminhos que coincidam com o índice.

  2. marque o caminho que será editado.

  3. assim faz o lstat(1) e encontra o índice que coincida com o caminho.

  4. assim faz o lstat(2) e encontra o índice que não coincida com o caminho.

  5. registrando uma nova versão nos conjuntos dos índices do bit "assuma como inalterado".

  6. e é assumido como inalterado.

  7. mesmo depois que você o edite.

  8. você pode contar sobre a alteração após o fato.

  9. agora verifica com lstat(2) e descobre o que foi alterado.

SKIP-WORKTREE BIT

O bit do Skip-worktree pode ser definido numa (longa) frase: Diga ao git para evitar escrever o arquivo no diretório de trabalho quando for razoavelmente possível, e trate o arquivo como inalterado quando ele não estiver presente no diretório de trabalho.

Note que nem todos os comandos do git prestarão atenção a este bit, e alguns, só são parcialmente compatíveis.

The update-index flags and the read-tree capabilities relating to the skip-worktree bit predated the introduction of the git-sparse-checkout[1] command, which provides a much easier way to configure and handle the skip-worktree bits. If you want to reduce your working tree to only deal with a subset of the files in the repository, we strongly encourage the use of git-sparse-checkout[1] in preference to the low-level update-index and read-tree primitives.

The primary purpose of the skip-worktree bit is to enable sparse checkouts, i.e. to have working directories with only a subset of paths present. When the skip-worktree bit is set, Git commands (such as switch, pull, merge) will avoid writing these files. However, these commands will sometimes write these files anyway in important cases such as conflicts during a merge or rebase. Git commands will also avoid treating the lack of such files as an intentional deletion; for example git add -u will not stage a deletion for these files and git commit -a will not make a commit deleting them either.

Although this bit looks similar to assume-unchanged bit, its goal is different. The assume-unchanged bit is for leaving the file in the working tree but having Git omit checking it for changes and presuming that the file has not been changed (though if it can determine without stat’ing the file that it has changed, it is free to record the changes). skip-worktree tells Git to ignore the absence of the file, avoid updating it when possible with commands that normally update much of the working directory (e.g. checkout, switch, pull, etc.), and not have its absence be recorded in commits. Note that in sparse checkouts (setup by git sparse-checkout or by configuring core.sparseCheckout to true), if a file is marked as skip-worktree in the index but is found in the working tree, Git will clear the skip-worktree bit for that file.

ÍNDICE DIVIDIDO

Este modo é projetado para repositórios com índices muito grandes e visa reduzir o tempo necessário para gravar repetidamente tais índices.

Nesse modo, o índice é dividido em dois arquivos, $GIT_DIR/index e $GIT_DIR/sharedindex.<SHA-1>. As alterações são acumuladas no $GIT_DIR/index, o índice dividido, enquanto o arquivo do índice compartilhado contém todas os lançamentos no índice e permanece inalterado.

Todas as alterações feitas índice que foi dividido são retornadas ao arquivo do índice compartilhado quando a quantidade de entradas no índice atinge um nível especificado através da variável de configuração splitIndex.maxPercentChange (consulte git-config[1]).

Sempre que um novo arquivo do índice compartilhado for criado, os arquivos do índice antigos que foram compartilhados são excluídos caso o tempo de alteração seja mais antigo do que o definido pela variável de configuração splitIndex.sharedIndexExpire (consulte git-config[1]).

Para evitar a exclusão de um arquivo do índice compartilhado que ainda esteja em uso, o seu horário de modificação é atualizado para o horário atual sempre que um novo índice dividido tiver como base o arquivo do índice compartilhado seja criado ou lido.

CACHE NÃO MONITORADO

Esse cache destina-se a acelerar os comandos que envolvem a determinação dos arquivos não monitorados, como o git status.

Esse recurso funciona gravando o mtime dos diretórios da árvore de trabalho e em seguida, omitindo a leitura dos diretórios e as chamadas da condição nos arquivos dos diretórios cujo mtime não tenha sido alterado. Para que isso funcione, o sistema operacional e o sistema de arquivos subjacentes devem alterar o campo do diretório st_mtime caso os arquivos no diretório forem adicionados, modificados ou excluídos.

Você pode testar se o sistema de arquivos é compatível com a opção --test-untracked-cache. A opção --untracked-cache usada para executar este teste de forma implícita nas versões mais antigas do Git, porém este não é mais o caso.

Caso queira ativar (ou desativar) este recurso, é mais fácil utilizar a variável de configuração core.untrackedCache (consulte git-config[1]) do que utilizar a opção --untracked-cache para o comando git update-index em cada repositório, especialmente se você quiser fazê-lo em todos os repositórios que você utiliza, pois é possível definir a variável de configuração como true (ou false) no seu $HOME/.gitconfig apenas uma vez e afetar todos os repositórios que você toque.

Quando a variável de configuração core.untrackedCache é alterada, o cache não monitorado é adicionado ou removido do índice da próxima vez que um comando lê o índice; enquanto quando --[no-|force-]untracked-cache são utilizados, o cache não monitorado é imediatamente adicionado ou removido do índice.

Antes da versão 2.17, o cache não monitorado apresentava um erro, ao substituir um diretório por um link simbólico para outro diretório, fazendo com que ele mostrasse de forma incorreta os arquivos monitorados pelo git como não monitorados. Consulte o "status: adicione um teste com falha mostrando um bug core.untrackedCache" commit com git.git. Uma solução alternativa para isso é (e isso pode funcionar para os outros erros que ainda não foram descobertos no futuro):

$ git -c core.untrackedCache=false status

Também foi demonstrado que este bug afeta os casos sem um link simbólico na reposição de um diretório por um arquivo quando se trata das estruturas internas do cache não monitorado, porém nenhum caso foi relatado onde isso tenha resultado na saída incorreta do comando "git status".

Também existem os casos onde os índices existentes escritos pelas versões do git anteriores a versão 2.17 referenciarem os diretórios que não existem mais, potencialmente fazendo com que muitos avisos de "não foi possível abrir o diretório" sejam impressos durante a execução do comando "git status". Estes são os novos avisos para problemas existentes que foram descartados anteriormente sem qualquer aviso prévio.

Assim como no bug descrito acima, a solução é executar um "status git" único com core.untrackedCache=false para liberar os dados ruins restantes.

MONITOR DO SISTEMA DE ARQUIVOS

Este recurso visa acelerar as operações do git para os repositórios que possuem grandes diretórios de trabalho.

Ele permite que o git trabalhe em conjunto com um monitor do sistema de arquivos (consulte git-fsmonitor--daemon[1] e a seção "fsmonitor-watchman" do githooks[5]) que pode informá-lo sobre quais os arquivos foram alterados. Isso permite que o git evite ter que fazer um lstat() em todo arquivo para localizar quais os arquivos que foram alterados.

Quando usado em conjunto com o cache não monitorado, pode melhorar ainda mais o desempenho, evitando o custo de varrer todo o diretório ativo à procura de novos arquivos.

Caso queira ativar (ou desativar) este recurso, é mais fácil utilizar a variável de configuração core.fsmonitor (consulte git-config[1]) do que utilizar a opção --fsmonitor para o comando git update-index em cada repositório, especialmente se você quiser fazê-lo em todos os repositórios que você utiliza, pois é possível definir a variável de configuração no seu $HOME/.gitconfig apenas uma vez e afetar todos os repositórios que você toque.

Quando a variável de configuração core.fsmonitor é alterada, o monitor do sistema de arquivos é adicionado ou removido do índice na próxima vez que um comando leia o índice. Quando --[no-]fsmonitor é usado, o monitor do sistema de arquivos é imediatamente adicionado ou removido do índice.

CONFIGURAÇÃO

The command honors core.filemode configuration variable. If your repository is on a filesystem whose executable bits are unreliable, this should be set to false (see git-config[1]). This causes the command to ignore differences in file modes recorded in the index and the file mode on the filesystem if they differ only on executable bit. On such an unfortunate filesystem, you may need to use git update-index --chmod=.

De maneira semelhante, caso a variável de configuração core.symlinks esteja definida como false (consulte git-config[1]) os links simbólicos serão verificados como arquivos simples e esse comando não modificará o modo de gravação do arquivo vindo de link simbólico para um arquivo regular.

The command looks at core.ignorestat configuration variable. See Using "assume unchanged" bit section above.

The command also looks at core.trustctime configuration variable. It can be useful when the inode change time is regularly modified by something outside Git (file system crawlers and backup systems use ctime for marking files processed) (see git-config[1]).

A extensão do cache não rastreado pode ser ativado através da configuração de variável core.untrackedCache (consulte git-config[1]).

OBSERVAÇÕES

Users often try to use the assume-unchanged and skip-worktree bits to tell Git to ignore changes to files that are tracked. This does not work as expected, since Git may still check working tree files against the index when performing certain operations. In general, Git does not provide a way to ignore changes to tracked files, so alternate solutions are recommended.

For example, if the file you want to change is some sort of config file, the repository can include a sample config file that can then be copied into the ignored name and modified. The repository can even include a script to treat the sample file as a template, modifying and copying it automatically.

GIT

Parte do conjunto git[1]

scroll-to-top