view es/template.tex @ 569:012631b248de

translated some templates chapter paragraphs
author Igor Támara <igor@tamarapatino.org>
date Sun, 28 Dec 2008 00:27:39 -0500
parents b05e35d641e4
children 1b8b19825994
line wrap: on
line source

\chapter{Personalizar los mensajes de Mercurial}
\label{chap:template}

Mercurial provee un poderoso mecanismo que permite controlar como
despliega la información.  El mecanismo se basa en plantillas.  Puede
usar plantillas para generar salida específica para una orden
particular o para especificar la visualización completa de la interfaz
web embebida.

\section{Usar estilos que vienen con Mercurial}
\label{sec:style}

Hay ciertos estilos listos que vienen con Mercurial.  Un estilo es
simplemente una plantilla predeterminada que alguien escribió e
instaló en un sitio en el cual Mercurial puede encontrarla.

Antes de dar un vistazo a los estilos que trae Mercurial, revisemos su
salida usual.

\interaction{template.simple.normal}

Es en cierta medida informativa, pero ocupa mucho espacio---cinco
líneas de salida por cada conjunto de cambios.  El estilo
\texttt{compact} lo reduce a tres líneas, presentadas de forma
suscinta.

\interaction{template.simple.compact}

El estilo de la \texttt{bitácora de cambios} vislumbra el poder
expresivo del sistema de plantillas de Mercurial.  Este estilo busca
seguir los estándares de bitácora de cambios del proyecto
GNU\cite{web:changelog}.

\interaction{template.simple.changelog}

No es una sorpresa que el estilo predeterminado de Mercurial se llame
\texttt{default}\ndt{predeterminado}.

\subsection{Especificar un estilo predeterminado}

Puede modificar el estilo de presentación que Mercurial usará para
toda orden vía el fichero \hgrc\, indicando el estilo que prefiere
usar.

\begin{codesample2}
  [ui]
  style = compact
\end{codesample2}

Si escribe un estilo, puede usarlo bien sea proveyendo la ruta a su
fichero de estilo o copiando su fichero de estilo a un lugar en el
cual Mercurial pueda encontrarlo(típicamente el subdirectorio
\texttt{templates} de su directorio de instalación de Mercurial).

\section{Órdenes que soportan estilos y plantillas}

Todas las órdenes de Mercurial``relacionadas con \texttt{log}'' le
permiten usar estilos y plantillas: \hgcmd{incoming}, \hgcmd{log},
\hgcmd{outgoing} y \hgcmd{tip}.

Al momento de la escritura del manual estas son las únicas órdenes que
soportan estilos y plantillas.  Dado que son las órdenes más
importantes que necesitan personalización, no ha habido muchas
solicitudes desde la comunidad de usuarios de Mercurial para añadir
soporte de plantillas y estilos a otras órdenes.

\section{Cuestiones básicas de plantillas}

Una plantilla de Mercurial es sencillamente una pieza de texto.
Cierta porción nunca cambia, otras partes se \emph{expanden}, o
reemplazan con texto nuevo cuando es necesario.

Antes de continuar, veamos de nuevo un ejemplo sencillo de la salida
usual de Mercurial:

\interaction{template.simple.normal}

Ahora, ejecutemos la misma orden, pero usemos una plantilla para
modificar su salida:

\interaction{template.simple.simplest}

El ejemplo anterior ilustra la plantilla más sencilla posible;  es
solamente una porción estática de código que se imprime una vez por
cada conjunto de cambios.  La opción \hgopt{log}{--template} de la
orden \hgcmd{log} indica a Mercurial usar el texto dado como la
plantilla cuando se imprime cada conjunto de cambios.

Observe que la cadena de plantilla anterior termina con el texto
``\Verb+\n+''.  Es una \emph{secuencia de control}, que le indica a
Mercurial imprimira una nueva línea al final de cada objeto de la
plantilla.  Si omite esta nueva línea, Mercurial colocará cada pieza
de salida seguida.  Si desea más detalles acerca de secuencias de
control, vea la sección~\ref{sec:template:escape}.

Una plantilla que imprime una cadena fija de texto siempre no es muy
útil; intentemos algo un poco más complejo.

\interaction{template.simple.simplesub}

Como puede ver, la cadena ``\Verb+{desc}+'' en la plantilla ha sido
reemplazada en la salida con la descricipción de cada conjunto de
cambios.  Cada vez que Mercurial encuentra texto encerrado entre
corchetes(``\texttt{\{}'' y ``\texttt{\}}''), intentará reemplazar los
corchetes y el texto con la expansión de lo que sea está adentro.
Para imprimir un corchete de forma literal, debe escaparlo, como se
describe en la sección~\ref{sec:template:escape}.

\section{Palabras claves más comunes en las plantillas}
\label{sec:template:keyword}

Puede empezar a escribir plantillas sencillas rápidamente con las
palabras claves descritas a continuación:

\begin{itemize}
\item[\tplkword{author}] Cadena.  El autor NO modificado del conjunto
  de cambios.
\item[\tplkword{branches}] Cadena.  El nombre de la rama en la cual se
  consignó el conjunto de cambios.  Será vacía si el nombre de la rama es
  \texttt{default}.
\item[\tplkword{date}] Información de fecha.  La fecha en la cual se
  consignó el conjunto de cambios.  \emph{No} es legible por un
  humano, debe pasarla por un firltro que la desplegará
  apropiadamente.  En la sección~\ref{sec:template:filter} hay más
  detalles acerca de filtros.  La fecha se expresa como un par de
  números.  El primer número corresponde a una marca de tiempo UNIX
  UTC(segundos desde el primero de enero de 1970); la segunda es el
  corrimiento horario de la zona horaria del UTC en la cual se encontraba
  quien hizo la consignación, en segundos.
\item[\tplkword{desc}] Cadena.  La descripción en texto del conjunto
  de cambios.
\item[\tplkword{files}] Lista de cadenas.  Todos los ficheros
  modificados, adicionados o eliminados por este conjunto de cambios.
\item[\tplkword{file\_adds}] Lista de cadenas.  Ficheros adicionados
  por este conjunto de cambios.
\item[\tplkword{file\_dels}] Lista de cadenas.  Ficheros eliminados
  por este conjunto de cambios.
\item[\tplkword{node}] Cadena.  El hash de identificación de este
  conjunto de cambios como una cadena hexadecimal de 40 caracteres.
\item[\tplkword{parents}] Lista de cadenas.  Los ancestros del
  conjunto de cambios.
\item[\tplkword{rev}] Entero.  El número de revisión del repositorio
  local.
\item[\tplkword{tags}] Lista de cadenas.  Todas las etiquetas
  asociadas al conjunto de cambios.
\end{itemize}

Unos experimentos sencillos nos mostrarán qué esperar cuando usamos
estas palabras claves; puede ver los resultados en la
figura~\ref{fig:template:keywords}.

\begin{figure}
  \interaction{template.simple.keywords}
  \caption{Template keywords in use}
  \label{fig:template:keywords}
\end{figure}

Como mencionamos anteriormente, la palabra clave de fecha no produce
salida legible por un humano, debemos tratarla de forma especial.
Esto involucra usar un \emph{filtro}, acerca de lo cual hay más en la
sección~\ref{sec:template:filter}.

\interaction{template.simple.datekeyword}

\section{Secuencias de Control}
\label{sec:template:escape}

El motor de plantillas de Mercurial reconoce las secuencias de control
más comunmente usadas dentro de las cadenas.  Cuando ve un backslash
(``\Verb+\+''), ve el caracter siguiente y sustituye los dos
caracteres con un reemplazo sencillo, como se describe a continuación:

\begin{itemize}
\item[\Verb+\textbackslash\textbackslash+] Backslash, ``\Verb+\+'',
  ASCII~134.
\item[\Verb+\textbackslash n+] Nueva línea, ASCII~12.
\item[\Verb+\textbackslash r+] Cambio de línea, ASCII~15.
\item[\Verb+\textbackslash t+] Tab, ASCII~11.
\item[\Verb+\textbackslash v+] Tab Vertical, ASCII~13.
\item[\Verb+\textbackslash \{+] Corchete abierto, ``\Verb+{+'', ASCII~173.
\item[\Verb+\textbackslash \}+] Corchete cerrado, ``\Verb+}+'', ASCII~175.
\end{itemize}

Como se indicó arriba, si desea que la expansión en una plantilla
contenga un caracter literal ``\Verb+\+'', ``\Verb+{+'', o
  ``\Verb+{+'', debe escaparlo.

\section{Uso de filtros con palabras claves}
\label{sec:template:filter}

Algunos de los resultados de la expansión de la plantilla no son
fáciles de usar de inmediato.  Mercurial le permite especificar una
cadena de \emph{filtros} opcionales para modificar el resultado de
expandir una palabra clave.  Ya ha visto el filtro usual
\tplkwfilt{date}{isodate} en acción con anterioridad para hacer
legible la fecha.

A continuación hay una lista de los filtros de Mercurial más
comunmente usados.  Ciertos filtros pueden aplicarse a cualquier
texto, otros pueden usarse únicamente en circunstancias específicas.
El nombre de cada filtro está seguido de la indicación de dónde puede
ser usado y una descripción de su efecto.

\begin{itemize}
\item[\tplfilter{addbreaks}] Cualquier texto. Añade una etiqueta XHTML
  ``\Verb+<br/>+'' antes del final de cada línea excepto en la final.
  Por ejemplo, ``\Verb+foo\nbar+'' se convierte en ``\Verb+foo<br/>\nbar+''.
\item[\tplkwfilt{date}{age}] palabra clave \tplkword{date}.  Muestra
  la edad de la fecha, relativa al tiempo actual. Ofrece una cadena como
  ``\Verb+10 minutes+''.
\item[\tplfilter{basename}] Cualquier texto, pero de utilidad sobre
  todo en palabras claves relativas a \tplkword{ficheros}.  Trata el
  texto como una ruta, retornando el nombre base.  Por ejemplo,
  ``\Verb+foo/bar/baz+'', se convierte en ``\Verb+baz+''.
\item[\tplkwfilt{date}{date}] \tplkword{date} keyword.  Render a date
  in a similar format to the Unix \tplkword{date} command, but with
  timezone included.  Yields a string like
  ``\Verb+Mon Sep 04 15:13:13 2006 -0700+''.
\item[\tplkwfilt{author}{domain}] Any text, but most useful for the
  \tplkword{author} keyword.  Finds the first string that looks like
  an email address, and extract just the domain component.  For
  example, ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+'' becomes
  ``\Verb+serpentine.com+''.
\item[\tplkwfilt{author}{email}] Any text, but most useful for the
  \tplkword{author} keyword.  Extract the first string that looks like
  an email address.  For example,
  ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+'' becomes
  ``\Verb+bos@serpentine.com+''.
\item[\tplfilter{escape}] Any text.  Replace the special XML/XHTML
  characters ``\Verb+&+'', ``\Verb+<+'' and ``\Verb+>+'' with
  XML entities.
\item[\tplfilter{fill68}] Any text.  Wrap the text to fit in 68
  columns.  This is useful before you pass text through the
  \tplfilter{tabindent} filter, and still want it to fit in an
  80-column fixed-font window.
\item[\tplfilter{fill76}] Any text.  Wrap the text to fit in 76
  columns.
\item[\tplfilter{firstline}] Any text.  Yield the first line of text,
  without any trailing newlines.
\item[\tplkwfilt{date}{hgdate}] \tplkword{date} keyword.  Render the
  date as a pair of readable numbers.  Yields a string like
  ``\Verb+1157407993 25200+''.
\item[\tplkwfilt{date}{isodate}] \tplkword{date} keyword.  Render the
  date as a text string in ISO~8601 format.  Yields a string like
  ``\Verb+2006-09-04 15:13:13 -0700+''.
\item[\tplfilter{obfuscate}] Any text, but most useful for the
  \tplkword{author} keyword.  Yield the input text rendered as a
  sequence of XML entities.  This helps to defeat some particularly
  stupid screen-scraping email harvesting spambots.
\item[\tplkwfilt{author}{person}] Any text, but most useful for the
  \tplkword{author} keyword.  Yield the text before an email address.
  For example, ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+''
  becomes ``\Verb+Bryan O'Sullivan+''.
\item[\tplkwfilt{date}{rfc822date}] \tplkword{date} keyword.  Render a
  date using the same format used in email headers.  Yields a string
  like ``\Verb+Mon, 04 Sep 2006 15:13:13 -0700+''.
\item[\tplkwfilt{node}{short}] Changeset hash.  Yield the short form
  of a changeset hash, i.e.~a 12-byte hexadecimal string.
\item[\tplkwfilt{date}{shortdate}] \tplkword{date} keyword.  Render
  the year, month, and day of the date.  Yields a string like
  ``\Verb+2006-09-04+''.
\item[\tplfilter{strip}] Any text.  Strip all leading and trailing
  whitespace from the string.
\item[\tplfilter{tabindent}] Any text.  Yield the text, with every line
  except the first starting with a tab character.
\item[\tplfilter{urlescape}] Any text.  Escape all characters that are
  considered ``special'' by URL parsers.  For example, \Verb+foo bar+
  becomes \Verb+foo%20bar+.
\item[\tplkwfilt{author}{user}] Any text, but most useful for the
  \tplkword{author} keyword.  Return the ``user'' portion of an email
  address.  For example,
  ``\Verb+Bryan O'Sullivan <bos@serpentine.com>+'' becomes
  ``\Verb+bos+''.
\end{itemize}

\begin{figure}
  \interaction{template.simple.manyfilters}
  \caption{Template filters in action}
  \label{fig:template:filters}
\end{figure}

\begin{note}
  If you try to apply a filter to a piece of data that it cannot
  process, Mercurial will fail and print a Python exception.  For
  example, trying to run the output of the \tplkword{desc} keyword
  into the \tplkwfilt{date}{isodate} filter is not a good idea.
\end{note}

\subsection{Combining filters}

It is easy to combine filters to yield output in the form you would
like.  The following chain of filters tidies up a description, then
makes sure that it fits cleanly into 68 columns, then indents it by a
further 8~characters (at least on Unix-like systems, where a tab is
conventionally 8~characters wide).

\interaction{template.simple.combine}

Note the use of ``\Verb+\t+'' (a tab character) in the template to
force the first line to be indented; this is necessary since
\tplkword{tabindent} indents all lines \emph{except} the first.

Keep in mind that the order of filters in a chain is significant.  The
first filter is applied to the result of the keyword; the second to
the result of the first filter; and so on.  For example, using
\Verb+fill68|tabindent+ gives very different results from
\Verb+tabindent|fill68+.


\section{From templates to styles}

A command line template provides a quick and simple way to format some
output.  Templates can become verbose, though, and it's useful to be
able to give a template a name.  A style file is a template with a
name, stored in a file.

More than that, using a style file unlocks the power of Mercurial's
templating engine in ways that are not possible using the command line
\hgopt{log}{--template} option.

\subsection{The simplest of style files}

Our simple style file contains just one line:

\interaction{template.simple.rev}

This tells Mercurial, ``if you're printing a changeset, use the text
on the right as the template''.

\subsection{Style file syntax}

The syntax rules for a style file are simple.

\begin{itemize}
\item The file is processed one line at a time.

\item Leading and trailing white space are ignored.

\item Empty lines are skipped.

\item If a line starts with either of the characters ``\texttt{\#}'' or
  ``\texttt{;}'', the entire line is treated as a comment, and skipped
  as if empty.

\item A line starts with a keyword.  This must start with an
  alphabetic character or underscore, and can subsequently contain any
  alphanumeric character or underscore.  (In regexp notation, a
  keyword must match \Verb+[A-Za-z_][A-Za-z0-9_]*+.)

\item The next element must be an ``\texttt{=}'' character, which can
  be preceded or followed by an arbitrary amount of white space.

\item If the rest of the line starts and ends with matching quote
  characters (either single or double quote), it is treated as a
  template body.

\item If the rest of the line \emph{does not} start with a quote
  character, it is treated as the name of a file; the contents of this
  file will be read and used as a template body.
\end{itemize}

\section{Style files by example}

To illustrate how to write a style file, we will construct a few by
example.  Rather than provide a complete style file and walk through
it, we'll mirror the usual process of developing a style file by
starting with something very simple, and walking through a series of
successively more complete examples.

\subsection{Identifying mistakes in style files}

If Mercurial encounters a problem in a style file you are working on,
it prints a terse error message that, once you figure out what it
means, is actually quite useful.

\interaction{template.svnstyle.syntax.input}

Notice that \filename{broken.style} attempts to define a
\texttt{changeset} keyword, but forgets to give any content for it.
When instructed to use this style file, Mercurial promptly complains.

\interaction{template.svnstyle.syntax.error}

This error message looks intimidating, but it is not too hard to
follow.

\begin{itemize}
\item The first component is simply Mercurial's way of saying ``I am
  giving up''.
  \begin{codesample4}
    \textbf{abort:} broken.style:1: parse error
  \end{codesample4}

\item Next comes the name of the style file that contains the error.
  \begin{codesample4}
    abort: \textbf{broken.style}:1: parse error
  \end{codesample4}

\item Following the file name is the line number where the error was
  encountered.
  \begin{codesample4}
    abort: broken.style:\textbf{1}: parse error
  \end{codesample4}

\item Finally, a description of what went wrong.
  \begin{codesample4}
    abort: broken.style:1: \textbf{parse error}
  \end{codesample4}
  The description of the problem is not always clear (as in this
  case), but even when it is cryptic, it is almost always trivial to
  visually inspect the offending line in the style file and see what
  is wrong.
\end{itemize}

\subsection{Uniquely identifying a repository}

If you would like to be able to identify a Mercurial repository
``fairly uniquely'' using a short string as an identifier, you can
use the first revision in the repository.
\interaction{template.svnstyle.id} 
This is not guaranteed to be unique, but it is nevertheless useful in
many cases.
\begin{itemize}
\item It will not work in a completely empty repository, because such
  a repository does not have a revision~zero.
\item Neither will it work in the (extremely rare) case where a
  repository is a merge of two or more formerly independent
  repositories, and you still have those repositories around.
\end{itemize}
Here are some uses to which you could put this identifier:
\begin{itemize}
\item As a key into a table for a database that manages repositories
  on a server.
\item As half of a \{\emph{repository~ID}, \emph{revision~ID}\} tuple.
  Save this information away when you run an automated build or other
  activity, so that you can ``replay'' the build later if necessary.
\end{itemize}

\subsection{Mimicking Subversion's output}

Let's try to emulate the default output format used by another
revision control tool, Subversion.
\interaction{template.svnstyle.short}

Since Subversion's output style is fairly simple, it is easy to
copy-and-paste a hunk of its output into a file, and replace the text
produced above by Subversion with the template values we'd like to see
expanded.
\interaction{template.svnstyle.template}

There are a few small ways in which this template deviates from the
output produced by Subversion.
\begin{itemize}
\item Subversion prints a ``readable'' date (the ``\texttt{Wed, 27 Sep
    2006}'' in the example output above) in parentheses.  Mercurial's
  templating engine does not provide a way to display a date in this
  format without also printing the time and time zone.
\item We emulate Subversion's printing of ``separator'' lines full of
  ``\texttt{-}'' characters by ending the template with such a line.
  We use the templating engine's \tplkword{header} keyword to print a
  separator line as the first line of output (see below), thus
  achieving similar output to Subversion.
\item Subversion's output includes a count in the header of the number
  of lines in the commit message.  We cannot replicate this in
  Mercurial; the templating engine does not currently provide a filter
  that counts the number of items it is passed.
\end{itemize}
It took me no more than a minute or two of work to replace literal
text from an example of Subversion's output with some keywords and
filters to give the template above.  The style file simply refers to
the template.
\interaction{template.svnstyle.style}

We could have included the text of the template file directly in the
style file by enclosing it in quotes and replacing the newlines with
``\verb!\n!'' sequences, but it would have made the style file too
difficult to read.  Readability is a good guide when you're trying to
decide whether some text belongs in a style file, or in a template
file that the style file points to.  If the style file will look too
big or cluttered if you insert a literal piece of text, drop it into a
template instead.

%%% Local Variables: 
%%% mode: latex
%%% TeX-master: "00book"
%%% End: