dimanche 12 février 2012

Getting started with mercurial: add, commit, tag, update, push

Update 12/09/24

Avec les liens suivant vous ne devriez pas avoir besoin de lire ce billet:

Preface

Pour commencer mercurial est le nom du logiciel et hg le nom de la commande. On utilise les deux pour parler de la commande et du logiciel.
Le plus simple pour installer mercurial est pip (voir l'article pip & virtualenv & virtualenvwrapper tryptique):
$ pip install mercurial
Concernant l'interface graphique je recommande pour le moment tortoisehg.
Munissez vous aussi de l'outil Meld qui facilite les opérations de fusion [merge].
Dans le cadre de ce tutoriel nous allons mettre en place une «application» qui va nous permettre de suivre un potager.

Facing the shiny silvery liquid metal element

Configuration

Pour commencer nous allons configurer mercurial, ouvrez le fichier ~/.hgrc et remplacer le contenu par ceci:
[ui]
username = {{ prenom }} {{ nom }} <{{ email }}>
verbose = True
editor = gedit
merge = meld

[extensions]
color = 
Remplacer {{ prenom }}, {{ nom }} {{ email }} par les bonnes valeurs.

Starting a new mercurial repository

La ligne de commande qui crée un nouveau dépôt (repository en anglais) est la suivante:
hg init [-e CMD] [--remotecmd CMD] [DEST]

       Initialize a new repository in the given directory. If the  given  directory
       does not exist, it will be created.

       If no directory is given, the current directory is used.

       It  is  possible  to  specify an ssh:// URL as the destination.  See hg help
       urls for more information.

       Returns 0 on success.

       Options:

       -e, --ssh
              specify ssh command to use

       --remotecmd
              specify hg command to run on the remote side

       --insecure
              do not verify server certificate (ignoring web.cacerts config)
Pour commencer le tutoriel nous allons partir d'un dossier vide. Créez un nouveau dossier et initialiser un dépôt mercurial à l’intérieur:
$ mkdir flower-power
$ cd flower-power
$ hg init
Mercurial a crée pour vous un dossier .hg dans le dossier flower-power. Mercurial se sert de ce dossier pour stocker certaines informations relative au dépôt. Hormis le dossier .hg, tout le contenu du dossier flower-power peut-être inclus dans le dépôt. flower-power est appelé le «dossier de travail».

Playing with files

Créez un fichier README:
$ touch README
Pour connaître l'état courant dossier de travail, les changements qui existent entre le dossier de travail et le dépôt, il faut utiliser la commande suivante:
hg status [OPTION]... [FILE]...

       Show  status of files in the repository. If names are given, only files that
       match are shown. Files that  are  clean  or  ignored  or  the  source  of  a
       copy/move   operation,  are  not  listed  unless  -c/--clean,  -i/--ignored,
       -C/--copies or -A/--all are given.  Unless options described with "show only
       ..." are given, the options -mardu are used.

       Option -q/--quiet hides untracked (unknown and ignored) files unless explic‐
       itly requested with -u/--unknown or -i/--ignored.

       Note   status may appear to disagree with diff if permissions  have  changed
              or  a  merge  has  occurred. The standard diff format does not report
              permission changes and diff only  reports  changes  relative  to  one
              merge parent.

       If one revision is given, it is used as the base revision.  If two revisions
       are given, the differences between them are shown. The --change  option  can
       also  be used as a shortcut to list the changed files of a revision from its
       first parent.

       The codes used to show the status of files are:

       M = modified
       A = added
       R = removed
       C = clean
       ! = missing (deleted by non-hg command, but still tracked)
       ? = not tracked
       I = ignored
         = origin of the previous file listed as A (added)

       Returns 0 on success.

       Options:

       -A, --all
              show status of all files

       -m, --modified
              show only modified files

       -a, --added
              show only added files

       -r, --removed
              show only removed files

       -d, --deleted
              show only deleted (but tracked) files

       -c, --clean
              show only files without changes

       -u, --unknown
              show only unknown (not tracked) files

       -i, --ignored
              show only ignored files

       -n, --no-status
              hide status prefix

       -C, --copies
              show source of copied files

       -0, --print0
              end filenames with NUL, for use with xargs

       --rev  show difference from revision

       --change
              list the changed files of a revision

       -I, --include
              include names matching the given patterns

       -X, --exclude
              exclude names matching the given patterns

       -S, --subrepos
              recurse into subrepositories

              aliases: st
Essayez la commande suivante:
$ hg status
? README
Mercurial vous informe à l'aide du «?» devant README que celui-ci n'est pas encore suivit.
Pour indiquer à mercurial qu'un fichier doit être suivit, il utiliser la commande add:
hg add [OPTION]... [FILE]...

       Schedule files to be version controlled and added to the repository.

       The files will be added to the repository at the next commit. To undo an add
       before that, see hg forget.

       If no names are given, add all files to the repository.

       An example showing how new (unknown) files are added automatically by hg add
       :

       $ ls
       foo.c
       $ hg status
       ? foo.c
       $ hg add
       adding foo.c
       $ hg status
       A foo.c

       Returns 0 if all files are successfully added.

       Options:

       -I, --include
              include names matching the given patterns

       -X, --exclude
              exclude names matching the given patterns

       -S, --subrepos
              recurse into subrepositories

       -n, --dry-run
              do not perform actions, just print output
Indiquez à mercurial qu'il faut suivre le fichier README:
$ hg add README
Vérifiez l'état du dépôt:
$ hg status
A README
Le «A» devant «README» signifie qu'un nouveau fichier va être suivit par mercurial. Ceci dit il n'est pas encore dans le dépôt.
La commande suivante permet de soumettre [commit] les modifications du dossier de travail au dépôt:
hg commit [OPTION]... [FILE]...

       Commit changes to the given files into the repository. Unlike a  centralized
       SCM,  this operation is a local operation. See hg push for a way to actively
       distribute your changes.

       If a list of files is omitted, all changes reported  by  hg  status will  be
       committed.

       If you are committing the result of a merge, do not provide any filenames or
       -I/-X filters.

       If no commit message is specified, Mercurial starts your  configured  editor
       where  you  can  enter a message. In case your commit fails, you will find a
       backup of your message in .hg/last-message.txt.

       See hg help dates for a list of formats valid for -d/--date.

       Returns 0 on success, 1 if nothing changed.

       Options:

       -A, --addremove
              mark new/missing files as added/removed before committing

       --close-branch
              mark a branch as closed, hiding it from the branch list

       -I, --include
              include names matching the given patterns

       -X, --exclude
              exclude names matching the given patterns

       -m, --message
              use text as commit message

       -l, --logfile
              read commit message from file

       -d, --date
              record the specified date as commit date

       -u, --user
              record the specified user as committer

              aliases: ci
Pour soumettre les changements au dépôt utilisé la commande suivante:
$ hg commit README
Un éditeur va apparaître avec le contenu suivant:
HG: Enter commit message.  Lines beginning with 'HG:' are removed.
HG: Leave message empty to abort commit.
HG: --
HG: user: Amirouche Boubekki <amirouche.boubekki@gmail.com>
HG: branch 'default'
HG: added README
Il s'agit d'un récapitulatif de ce que vous allez soumettre au dépôt. La dernière ligne indique que vous allez ajouter un fichier. Modifiez le contenu de l’éditeur comme bon vous semble en gardant à l'esprit que la première ligne du fichier sert de résumé et les lignes suivantes forme le corps du message:
added a README file

README will contain a description of the project I use it in a RDD process
HG: Enter commit message.  Lines beginning with 'HG:' are removed.
HG: Leave message empty to abort commit.
HG: --
HG: user: Amirouche Boubekki <amirouche.boubekki@gmail.com>
HG: branch 'default'
HG: added README
Sauvegardez le contenu du fichier et quittez l'éditeur. Mercurial reprend la main et réalise la soumission que vous avez demandez:
README
committed changeset 1:4b09b84648e1
Mercurial nous notifie qu'il a bien ajouter README, le changement soumis est identifié localement par la valeur numérique «1» et a pour identifiant unique «4b09b84648e1».
Verifiez l'état du dépot:
$ hg st
hg rend la main sans afficher de message dans la console c'est que l'état du dépôt et du dossier de travail sont identiques.
Modifiez le fichier README et voyez ce qu'en pense mercurial:
$ echo "Flower Power Almanac" > README
$ hg st
M README
Un nouveau message de la part de mercurial, qui cette fois annonce que le fichier README est modifié. Soumettez ces nouvelles modifications au dépot à l'aide de la commande suivantes:
$ hg commit README -m "added a title"
README
committed changeset 2:0123456789ab
L'option «-m» permet de passer un résumé directement depuis la ligne de commande
Accélérons l'écriture de l'almanac et ajoutant un fichier TODO et un fichier LICENSE:
echo "list flowers" > TODO
echo "This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 France License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA." > LICENSE
Est ce que cela dérange mercurial ?
$ hg st
? LICENSE
? TODO
Vraisemblablement non, il indique qu'il y a deux fichiers non suivit dans le dossier de travail. Indiquez à mercurial qu'il faut suivre tous les fichiers non suivit à l'aide de la commande suivante:
$ hg add
ajout de LICENSE
ajout de TODO
Nous allons soumettre séparément les deux fichiers afin d'avoir un historique clair des modifications:
$ hg commit LICENSE -m "added a LICENSE file"
LICENSE
committed changeset 3:29b4e654cbe3
$ hg commit TODO -m "added a TODO file"
TODO
committed changeset 4:e5d45190f021
Il était aussi possible de soumettre toutes les modifications du dossier de travail à l'aide de l'une de ces commandes:
$ hg commit LICENSE TODO -m "added LICENSE and TODO file"
$ hg commit -m "added LICENSE and TODO file"
C'est généralement une mauvaise idée de faire cela car l'historique est plus difficile à lire. Malgré tout cela est possible car il arrive que vous deviez faire une action sur plusieurs fichiers comme par exemple corriger des typos, ou dans le cas du développement logiciel le renommage d'une fonction qui peux impacter plusieurs fichiers.
Ajoutez votre nom dans le fichier README et LICENSE et soumettez les modifications en masses à l'aide de la commande suivante:
$ hg commit -m "added my name"
LICENSE
README
committed changeset 5:8d3dab904982

Tagging for the win

Mercurial offre la possibilité de nommer les changements réalisés à l'aide d'étiquette (tag en anglais):
hg tag [-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME
      Name a particular revision using <name>.

       Tags are used to name particular revisions of the repository  and  are  very
       useful  to  compare  different  revisions, to go back to significant earlier
       versions or to mark branch points as releases, etc. Changing an existing tag
       is normally disallowed; use -f/--force to override.

       If no revision is given, the parent of the working directory is used, or tip
       if no revision is checked out.

       To facilitate version control, distribution, and merging of tags,  they  are
       stored as a file named ".hgtags" which is managed similarly to other project
       files and can be hand-edited if necessary. This also means that tagging cre‐
       ates  a  new  commit.  The  file ".hg/localtags" is used for local tags (not
       shared among repositories).

       Tag commits are usually made at the head of a branch. If the parent  of  the
       working  directory  is  not  a branch head, hg tag aborts; use -f/--force to
       force the tag commit to be based on a non-head changeset.

       See hg help dates for a list of formats valid for -d/--date.

       Since tag names have priority over  branch  names  during  revision  lookup,
       using an existing branch name as a tag name is discouraged.

       Returns 0 on success.

       Options:

       -f, --force
              force tag

       -l, --local
              make the tag local

       -r, --rev
              revision to tag

       --remove
              remove a tag

       -e, --edit
              edit commit message

       -m, --message
              use <text> as commit message

       -d, --date
              record the specified date as commit date

       -u, --user
              record the specified user as committer
La commande qui tag la version courante avec «0.1» du dépôt est la suivante:
$ hg tag 0.1
Vous pouvez aussi taggez une ancienne version [revision] à l'aide de l'option -r:
$ hg tag 0.0 -r 0
Pour lister les tags utiliser tag au pluriel comme commande:
$ hg tags
Stay on the edge
La commande update (qui pour synonyme checkout) vous permet de vous deplacer dans l'historique:

hg update [-c] [-C] [-d DATE] [[-r] REV]

alias : up, checkout, co

update working directory (or switch revisions)

    Update the repository's working directory to the specified changeset. If
    no changeset is specified, update to the tip of the current named branch.

    If the changeset is not a descendant of the working directory's parent,
    the update is aborted. With the -c/--check option, the working directory
    is checked for uncommitted changes; if none are found, the working
    directory is updated to the specified changeset.

    Update sets the working directory's parent revison to the specified
    changeset (see "hg help parents").

    The following rules apply when the working directory contains uncommitted
    changes:

    1. If neither -c/--check nor -C/--clean is specified, and if the requested
       changeset is an ancestor or descendant of the working directory's
       parent, the uncommitted changes are merged into the requested changeset
       and the merged result is left uncommitted. If the requested changeset
       is not an ancestor or descendant (that is, it is on another branch),
       the update is aborted and the uncommitted changes are preserved.
    2. With the -c/--check option, the update is aborted and the uncommitted
       changes are preserved.
    3. With the -C/--clean option, uncommitted changes are discarded and the
       working directory is updated to the requested changeset.

    Use null as the changeset to remove the working directory (like "hg clone
    -U").

    If you want to revert just one file to an older revision, use "hg revert
    [-r REV] NAME".

    See "hg help dates" for a list of formats valid for -d/--date.

    Returns 0 on success, 1 if there are unresolved files.

options:

 -C --clean     discard uncommitted changes (no backup)
 -c --check     update across branches if no uncommitted changes
 -d --date DATE tipmost revision matching date
 -r --rev REV   revision

global options:

 -R --repository REPO   repository root directory or name of overlay bundle
                        file
    --cwd DIR           change working directory
 -y --noninteractive    do not prompt, automatically pick the first choice for
                        all prompts
 -q --quiet             suppress output
 -v --verbose           enable additional output
    --config CONFIG [+] set/override config option (use 'section.name=value')
    --debug             enable debugging output
    --debugger          start debugger
    --encoding ENCODE   set the charset encoding (défaut: UTF-8)
    --encodingmode MODE set the charset encoding mode (défaut: strict)
    --traceback         always print a traceback on exception
    --time              time how long the command takes
    --profile           print command execution profile
    --version           output version information and exit
 -h --help              display help and exit
    --color TYPE        when to colorize (boolean, always, auto, or never)
                        (défaut: auto)

[+] marked option can be specified multiple times
Vous pouvez utiliser de manière indifférente un tag, un numéro de version locale ou un hash si il n'y a pas de conflit. Pour revenir à la révision locale 1:
$ hg update 1
resolving manifests
suppression de .hgtags
0 files updated, 0 files merged, 1 files removed, 0 files unresolved
Utilisé sans option supplémentaire, cette commande vous permet de charger dans le repertoire de travail le "tip" c'est à dire la derniere version disponible localement:
$ hg update
resolving manifests
getting .hgtags
1 files updated, 0 files merged, 0 files removed, 0 files unresolved
Sharing
Pour partager votre dépôt avec le reste du monde vous pouvez utiliser bitbucket. Après avoir crée un compte et un dépôt, vous pouvez pousser [push] votre dépôt:
hg push [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]

push changes to the specified destination

    Push changesets from the local repository to the specified destination.

    This operation is symmetrical to pull: it is identical to a pull in the
    destination repository from the current one.

    By default, push will not allow creation of new heads at the destination,
    since multiple heads would make it unclear which head to use. In this
    situation, it is recommended to pull and merge before pushing.

    Use --new-branch if you want to allow push to create a new named branch
    that is not present at the destination. This allows you to only create a
    new branch without forcing other changes.

    Use -f/--force to override the default behavior and push all changesets on
    all branches.

    If -r/--rev is used, the specified revision and all its ancestors will be
    pushed to the remote repository.

    Please see "hg help urls" for important details about "ssh://" URLs. If
    DESTINATION is omitted, a default path will be used.

    Returns 0 if push was successful, 1 if nothing to push.

options:

 -f --force                 force push
 -r --rev REV [+]           a changeset intended to be included in the
                            destination
 -B --bookmark BOOKMARK [+] bookmark to push
 -b --branch BRANCH [+]     a specific branch you would like to push
    --new-branch            allow pushing a new branch
 -e --ssh CMD               specify ssh command to use
    --remotecmd CMD         specify hg command to run on the remote side
    --insecure              do not verify server certificate (ignoring
                            web.cacerts config)

[+] marked option can be specified multiple times

global options:

 -R --repository REPO   repository root directory or name of overlay bundle
                        file
    --cwd DIR           change working directory
 -y --noninteractive    do not prompt, automatically pick the first choice for
                        all prompts
 -q --quiet             suppress output
 -v --verbose           enable additional output
    --config CONFIG [+] set/override config option (use 'section.name=value')
    --debug             enable debugging output
    --debugger          start debugger
    --encoding ENCODE   set the charset encoding (défaut: UTF-8)
    --encodingmode MODE set the charset encoding mode (défaut: strict)
    --traceback         always print a traceback on exception
    --time              time how long the command takes
    --profile           print command execution profile
    --version           output version information and exit
 -h --help              display help and exit
    --color TYPE        when to colorize (boolean, always, auto, or never)
                        (défaut: auto)

[+] marked option can be specified multiple times
Pour réussir la commande suivante il faut bien sur une adresse valide:
$ hg push ssh://hg@bitbucket.org/abki/almanac

Aucun commentaire:

Enregistrer un commentaire