Git
Português (Brasil) ▾Topics ▾Latest version ▾ git-for-each-ref last updated in 2.45.0

NOME

git-for-each-ref - Informações de saída de cada referência

RESUMO

git for-each-ref [--count=<contagem>] [--shell|--perl|--python|--tcl]
		   [(--sort=<chave>)…​] [--format=<formato>]
		   [ --stdin | <padrão>…​ ]
		   [--points-at=<objeto>]
		   [--merged[=<objeto>]] [--no-merged[=<objeto>]]
		   [--contains[=<objeto>]] [--no-contains[=<objeto>]]
		   [--exclude=<padrão> …​]

DESCRIÇÃO

Iterate over all refs that match <pattern> and show them according to the given <format>, after sorting them according to the given set of <key>. If <count> is given, stop after showing that many refs. The interpolated values in <format> can optionally be quoted as string literals in the specified host language allowing their direct evaluation in that language.

OPÇÕES

<padrão>…​

Caso uma ou mais padrões sejam utilizados, serão exibidos apenas as referências que coincidam com um dos padrões apresentados utilizando fnmatch(3) ou literal, neste último caso, apenas caso coincida completamente seja desde o início ou até uma barra.

--stdin

Caso a opção --stdin seja usada, então a lista de padrões é lida a partir de entrada predefinida em vez da lista de argumentos.

--count=<count>

By default the command shows all refs that match <pattern>. This option makes it stop after showing that many refs.

--sort=<chave>

A field name to sort on. Prefix - to sort in descending order of the value. When unspecified, refname is used. You may use the --sort=<key> option multiple times, in which case the last key becomes the primary key.

--format=<formato>

A string that interpolates %(fieldname) from a ref being shown and the object it points at. In addition, the string literal %% renders as % and %xx - where xx are hex digits - renders as the character with hex code xx. For example, %00 interpolates to \0 (NUL), %09 to \t (TAB), and %0a to \n (LF).

When unspecified, <format> defaults to %(objectname) SPC %(objecttype) TAB %(refname).

--color[=<quando>]

Respeite todas as cores usadas com a opção --format. O campo <quando> deve ser always, never ou auto (comporte-se como always caso <quando> esteja ausente).

--shell
--perl
--python
--tcl

If given, strings that substitute %(fieldname) placeholders are quoted as string literals suitable for the specified host language. This is meant to produce a scriptlet that can directly be `eval`ed.

--points-at=<objeto>

Listar apenas as referências que apontem para o objeto especificado.

--merged[=<objeto>]

Liste apenas as referências cujas dicas são acessíveis a partir do commit especificado (ou HEAD caso nenhum seja especificado).

--no-merged[=<objeto>]

Liste apenas as referências cujas dicas não podem ser acessadas a partir do commit especificado (ou HEAD caso nenhum seja especificado).

--contains[=<objeto>]

Liste apenas as referências que contenham os commits especificados (ou HEAD caso nenhum seja especificado).

--no-contains[=<objeto>]

Listar apenas as referências que não contenham os commits especificados (ou HEAD caso nenhum seja especificado).

--ignore-case

As referências de classificação e filtragem não diferenciam as maiúsculas de minúsculas.

--omit-empty

Não imprima uma nova linha após a formatação das referências onde o formato se expande para a string vazia.

--exclude=<padrão>

Caso um ou mais padrões sejam fornecidos, somente as referências que não corresponderem a nenhum padrão que tenha sido excluído serão mostradas. A correspondência é feita usando as mesmas regras do <padrão> acima.

NOME DOS CAMPOS

Há vários valores dos campos estruturados nas referências dos objetos que podem ser utilizados para interpolação da saída resultante ou como chaves de classificação.

Os seguintes nomes podem ser utilizados para todos os objetos, :

refname

The name of the ref (the part after $GIT_DIR/). For a non-ambiguous short name of the ref append :short. The option core.warnAmbiguousRefs is used to select the strict abbreviation mode. If lstrip=<N> (rstrip=<N>) is appended, strips <N> slash-separated path components from the front (back) of the refname (e.g. %(refname:lstrip=2) turns refs/tags/foo into foo and %(refname:rstrip=2) turns refs/tags/foo into refs). If <N> is a negative number, strip as many path components as necessary from the specified end to leave -<N> path components (e.g. %(refname:lstrip=-2) turns refs/tags/foo into tags/foo and %(refname:rstrip=-1) turns refs/tags/foo into refs). When the ref does not have enough components, the result becomes an empty string if stripping with positive <N>, or it becomes the full refname if stripping with negative <N>. Neither is an error.

O strip pode ser utilizado como sinônimo de lstrip.

objecttype

O tipo do objeto (blob, tree, commit, tag).

objectsize

The size of the object (the same as git cat-file -s reports). Append :disk to get the size, in bytes, that the object takes up on disk. See the note about on-disk sizes in the CAVEATS section below.

objectname

The object name (aka SHA-1). For a non-ambiguous abbreviation of the object name append :short. For an abbreviation of the object name with desired length append :short=<length>, where the minimum length is MINIMUM_ABBREV. The length may be exceeded to ensure unique object names.

deltabase

This expands to the object name of the delta base for the given object, if it is stored as a delta. Otherwise it expands to the null object name (all zeroes).

upstream

The name of a local ref which can be considered “upstream” from the displayed ref. Respects :short, :lstrip and :rstrip in the same way as refname above. Additionally respects :track to show "[ahead N, behind M]" and :trackshort to show the terse version: ">" (ahead), "<" (behind), "<>" (ahead and behind), or "=" (in sync). :track also prints "[gone]" whenever unknown upstream ref is encountered. Append :track,nobracket to show tracking information without brackets (i.e "ahead N, behind M").

Para qualquer ramificação monitorada remotamente como %(upstream), %(upstream:nomeremoto) e %(upstream:remoteref) consulte o nome remoto e o nome "ref" monitorado remotamente e assim sucessivamente. Em outras palavras, o ramo monitorado remotamente pode ser atualizado de forma explicita ou individualmente utilizando o "refspec" %(upstream:remoteref):%(upstream) para que seja capturado em %(upstream:remotename).

Has no effect if the ref does not have tracking information associated with it. All the options apart from nobracket are mutually exclusive, but if used together the last option is selected.

push

O nome de uma "ref" local que representa a localização @{push} para uma ref que está sendo exibido. Respeita as opções :short, :lstrip, :rstrip, :track, :trackshort, :remotename, e :remoteref; assim como a opção upstream. Produz uma cadeia de caracteres vazia caso nenhum @{push} "ref" esteja configurada.

HEAD

* caso HEAD corresponda à ref atual (a ramificação que foi verificada), caso contrário ' '.

color

Change output color. Followed by :<colorname>, where color names are described under Values in the "CONFIGURATION FILE" section of git-config[1]. For example, %(color:bold red).

align

Left-, middle-, or right-align the content between %(align:…​) and %(end). The "align:" is followed by width=<width> and position=<position> in any order separated by a comma, where the <position> is either left, right or middle, default being left and <width> is the total length of the content with alignment. For brevity, the "width=" and/or "position=" prefixes may be omitted, and bare <width> and <position> used instead. For instance, %(align:<width>,<position>). If the contents length is more than the width then no alignment is performed. If used with --quote everything in between %(align:…​) and %(end) is quoted, but if nested then only the topmost level performs quoting.

if

Used as %(if)…​%(then)…​%(end) or %(if)…​%(then)…​%(else)…​%(end). If there is an atom with value or string literal after the %(if) then everything after the %(then) is printed, else if the %(else) atom is used, then everything after %(else) is printed. We ignore space when evaluating the string before %(then), this is useful when we use the %(HEAD) atom which prints either "*" or " " and we want to apply the if condition only on the HEAD ref. Append ":equals=<string>" or ":notequals=<string>" to compare the value between the %(if:…​) and %(then) atoms with the given string.

symref

O ref ao qual determinado ref simbólico se refere. Caso não seja um ref simbólico, nada será impresso. Respeita as opções :short, :lstrip e :rstrip da mesma maneira que o refname acima.

assinatura

A assinatura GPG de um commit.

signature:grade

Mostra "G" para uma assinatura boa (válida), "B" para uma assinatura ruim, "U" para uma assinatura boa com validade desconhecida, "X" para uma assinatura boa que expirou, "Y" para uma assinatura boa feita por uma chave expirada, "R" para uma assinatura boa feita por uma chave revogada, "E" caso a assinatura não possa ser verificada (por exemplo, pela falta da chave) e "N" para nenhuma assinatura.

signature:signer

O signatário de uma assinatura GPG de um commit.

signature:key

A chave de uma assinatura GPG de um commit.

signature:fingerprint

A impressão digital de uma assinatura GPG de um commit.

signature:primarykeyfingerprint

A impressão digital da chave primária da assinatura GPG de um commit.

signature:trustlevel

O nível de confiança de uma assinatura GPG de um commit. Os possíveis resultados são ultimate, fully, marginal, never e undefined.

worktreepath

O caminho absoluto para a árvore de trabalho onde a "ref" foi averiguada, caso estiveja em qualquer árvore de trabalho vinculada. Caso contrário, uma sequência vazia.

ahead-behind:<committish>

Dois números inteiros, separados por um espaço, demonstrando a quantidade de commits a frente e atrás, respectivamente, ao comparar a ref gerada com o <committish> no formato especificado.

describe[:options]

Um nome legível para humanos, como git-describe[1]; uma string vazia para commits indescritíveis. A string describe pode ser seguida por dois-pontos e uma ou mais opções separadas por vírgulas.

tags=<valor-bool>

Em vez de considerar apenas as tags anotadas, considere também as tags simples; consulte a opção correspondente em git-describe[1] para obter mais detalhes.

abbrev=<número>

Use pelo menos <número> de dígitos hexadecimais; consulte a opção correspondente em git-describe[1] para obter mais detalhes.

match=<padrão>

Considere apenas as tags informadas que correspondam ao padrão glob(7), excluindo o prefixo "refs/tags/"; consulte a opção correspondente em git-describe[1] para obter mais detalhes.

exclude=<padrão>

Não considere as tags informadas que correspondam ao padrão glob(7), excluindo o prefixo "refs/tags/"; consulte a opção correspondente em git-describe[1] para obter mais detalhes.

In addition to the above, for commit and tag objects, the header field names (tree, parent, object, type, and tag) can be used to specify the value in the header field. Fields tree and parent can also be used with modifier :short and :short=<length> just like objectname.

For commit and tag objects, the special creatordate and creator fields will correspond to the appropriate date or name-email-date tuple from the committer or tagger fields depending on the object type. These are intended for working on a mix of annotated and lightweight tags.

For tag objects, a fieldname prefixed with an asterisk (*) expands to the fieldname value of the peeled object, rather than that of the tag object itself.

Fields that have name-email-date tuple as its value (author, committer, and tagger) can be suffixed with name, email, and date to extract the named component. For email fields (authoremail, committeremail and taggeremail), :trim can be appended to get the email without angle brackets, and :localpart to get the part before the @ symbol out of the trimmed email. In addition to these, the :mailmap option and the corresponding :mailmap,trim and :mailmap,localpart can be used (order does not matter) to get values of the name and email according to the .mailmap file or according to the file set in the mailmap.file or mailmap.blob configuration variable (see gitmailmap[5]).

Os dados brutos num objeto são raw.

raw:size

O tamanho dos dados brutos do objeto.

Observe que --format=%(raw) não pode ser usado com as opções --python, --shell, --tcl, pois tais linguagens podem não ser compatíveis com dados binários arbitrários na string do tipo da variável deles.

A mensagem num commit ou na etiqueta do objeto é contents, onde o contents:<parte> pode ser utilizado para extrair várias partes de:

contents:size

O tamanho em bytes da mensagem do commit ou da tag.

contents:subject

The first paragraph of the message, which typically is a single line, is taken as the "subject" of the commit or the tag message. Instead of contents:subject, field subject can also be used to obtain same results. :sanitize can be appended to subject for subject line suitable for filename.

contents:body

O restante do commit ou a etiqueta da mensagem que segue o "assunto".

contents:signature

A assinatura GPG opcional da tag.

contents:lines=N

As primeiras N linhas da mensagem.

Além disso, os trailers interpretados por git-interpret-trailers[1] são obtidos como trailers[:opções] (ou usando o pseudônimo histórico contents:trailers[:opções]). Para conhecer os valores válidos para as [:opções], consulte a seção trailers do git-log[1].

For sorting purposes, fields with numeric values sort in numeric order (objectsize, authordate, committerdate, creatordate, taggerdate). All other fields are used to sort in their byte-value order.

Também existe uma opção de classificação por versões utilizando o nome do campo version:refnamee ou o seu apelido v:refname.

In any case, a field name that refers to a field inapplicable to the object referred by the ref does not cause an error. It returns an empty string instead.

Como um caso especial para os campos do tipo data, você pode especificar um formato para a data adicionando : seguido pelo nome do formato da data (veja quais os valores a opção --date assume em git-rev-list[1]).

Some atoms like %(align) and %(if) always require a matching %(end). We call them "opening atoms" and sometimes denote them as %($open).

Quando uma citação específica da linguagem de script está em vigor, tudo entre um átomo de abertura no topo do nível e o seu %(end) correspondente é avaliado de acordo com a semântica do átomo de abertura e apenas o resultado do topo seja citado.

EXEMPLOS

An example directly producing formatted text. Show the most recent 3 tagged commits:

#!/bin/sh

git for-each-ref --count=3 --sort='-*authordate' \
--format='From: %(*authorname) %(*authoremail)
Subject: %(*subject)
Date: %(*authordate)
Ref: %(*refname)

%(*body)
' 'refs/tags'

A simple example showing the use of shell eval on the output, demonstrating the use of --shell. List the prefixes of all heads:

#!/bin/sh

git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
while read entry
do
	eval "$entry"
	echo `dirname $ref`
done

Um relatório um pouco mais elaborado sobre as tags, demonstrando que o formato pode ser um script inteiro:

#!/bin/sh

fmt='
	r=%(refname)
	t=%(*objecttype)
	T=${r#refs/tags/}

	o=%(*objectname)
	n=%(*authorname)
	e=%(*authoremail)
	s=%(*subject)
	d=%(*authordate)
	b=%(*body)

	kind=Tag
	if test "z$t" = z
	then
		# could be a lightweight tag
		t=%(objecttype)
		kind="Lightweight tag"
		o=%(objectname)
		n=%(authorname)
		e=%(authoremail)
		s=%(subject)
		d=%(authordate)
		b=%(body)
	fi
	echo "$kind $T points at a $t object $o"
	if test "z$t" = zcommit
	then
		echo "O commit foi criado por $n $e
at $d, and titled

    $s

A sua mensagem diz:
"
		echo "$b" | sed -e "s/^/    /"
		echo
	fi
'

eval=`git for-each-ref --shell --format="$fmt" \
	--sort='*objecttype' \
	--sort=-taggerdate \
	refs/tags`
eval "$eval"

An example to show the usage of %(if)…​%(then)…​%(else)…​%(end). This prefixes the current branch with a star.

git for-each-ref --format="%(if)%(HEAD)%(then)* %(else)  %(end)%(refname:short)" refs/heads/

An example to show the usage of %(if)…​%(then)…​%(end). This prints the authorname, if present.

git for-each-ref --format="%(refname)%(if)%(authorname)%(then) Criado por: %(authorname)%(end)"

RESSALVAS

Observe que os tamanhos dos objetos no disco são relatados com precisão, porém é preciso ter cuidado ao tirar conclusões sobre quais as refs ou os objetos sejam responsáveis pela utilização do disco. O tamanho de um objeto não delta compactado, pode ser muito maior do que o tamanho dos objetos onde o delta seja contra ele, porém a escolha de qual objeto é a base e qual é o delta é arbitrária e está sujeita a alterações durante um reempacotamento.

Observe também que as várias cópias de um objeto podem estar presentes no banco de dados dos objetos; neste caso, é indefinido qual o tamanho da cópia ou da base delta que será relatada.

OBSERVAÇÕES

Ao combinar diversos filtros a opção --contains e a opção --no-contains, faz referências apenas aos que contenha pelo menos um dos commits --contains e não contenha nenhum dos commits mostrados com --no-contains.

Ao combinar diversos filtros a opção --merged e a opção --no-merged, faz referências apenas aos que sejam acessíveis a partir um dos commits --merged e de nenhum dos commits mostrados com --no-merged.

VEJA TAMBÉM

GIT

Parte do conjunto git[1]

scroll-to-top