Outils pour utilisateurs

Outils du site


issue86:command_conquer

Last month we covered a series of examples when it came to using Git in combination with Github. Within this article, I asked if there was any interest in an article on hosting/creating your own git repository host. Turns out… there is. As such, we'll be dedicating this month's article to creating and hosting your own git repositories, as well as discussing how to manage specific branches (such as: cloning a single branch from a repository, merging branches, creating a new one, etc.).

Le mois dernier, nous avons passé en revue une série d'exemples sur l'utilisation de Git en combinaison avec Github. Dans l'article, je demandais si des gens seraient intéressés par un article qui décrirait l'hébergement/la création d'un dépôt hôte git. Il s'avère que… oui. Donc, cet article va être consacré à la création et l'hébergement de vos propres dépôts git ; il va aussi parler de comment gérer les branches spécifiques (comme cloner une seule branche à partir d'un dépôt, fusionner des branches, en créer une nouvelle, etc.).

Git Server The easiest way to configure a git server would be to simply install git on the server, and configure an SSH server. As this was the method I used, it will be what we focus on this month, and I will assume you have a working SSH server installed on the remote machine already. If you prefer to try this out on a local machine and simply copy repositories back and forth, you can simply use normal file paths instead of the SSH format.

Serveur Git

La façon la plus facile de configurer un serveur git serait, simplement, d'installer git sur le serveur et de configurer un SSH. Comme c'est la méthode que j'ai utilisée, ce sera notre centre d'intérêt de ce mois et je vais supposer que vous avez déjà un serveur SSH en état de marche sur la machine distante. Si vous préférez le tester sur une machine locale et copier simplement des dossiers de l'un à l'autre et vice versa, vous pouvez utiliser les chemins de fichiers normaux plutôt que le format SSH.

Creating a new repository Assuming this is a remote host, you'll need to SSH into the machine (using the same user you plan on utilizing as the git user). Once you've done that, you're ready to create the repository with the following: git –bare init <folder>.git If the folder doesn't exist, it will be created. I would recommend keeping the server organized by placing all git repositories within a sub-folder of the user's home folder. Something like /home/gituser/git-repos/. As for the command itself: –bare tells git to initialize the repository without a separate .git folder. It seems the standard practice is to use a bare repository for shared repositories (i.e. ones you want people to clone/push/pull/fetch). If you're creating this repository on a local machine and plan to only occasionally access the folder via another machine, you may be fine without the –bare switch. Otherwise you shouldn't run into issues one way or the other.

Créer un nouveau dépôt

Partant de l'hypothèse d'un dépôt distant, vous avez besoin d'un accès SSH à la machine (en utilisant le même identifiant que celui que vous prévoyez pour git). Quand c'est fait, vous êtes prêt à créer le dépôt comme suit :

git –bare init <folder>.git

Si le répertoire n'existe pas, il sera créé. Pour une bonne organisation du serveur, je vous recommanderais de placer tous les dépôts git dans un sous-répertoire de votre répertoire home personnel. Quelque chose comme /home/gituser/git-repos/. Pour ce qui est de la commande elle-même : --bare indique à git d'initialiser le dépôt sans répertoire .git séparé. Il semble que l'usage est d'utiliser un dépôt vide pour les dépôts partagés (c'est-à-dire ceux pour lesquels vous acceptez que les gens clonent/chargent/déchargent/récupèrent). Si vous créez ce dépôt sur une machine locale en ne prévoyant qu'un accès occasionnel à ce dépôt depuis une autre machine, il se peut que ce soit bien sans le commutateur --bare. Quelle que soit la solution choisie, vous ne devriez pas rencontrer de problème.

Adding files to the repository Regardless of whether you initialized the repository in an empty folder, or a folder you've already filled, nothing will be added to the actual repository by default. You'll need to run: git add . Before anything is added. Once you've added it, you'll also need to commit the changes with: git commit -m “Message”

Ajouter des fichiers dans un dépôt

Sans se soucier de savoir si vous avez initialisé le dépôt dans un répertoire vide ou utilisé un répertoire déjà rempli, par défaut rien n'est ajouté au dépôt. Vous aurez besoin de lancer :

git add

avant d'y ajouter quoi que ce soit. Une fois que vous l'avez ajouté, vous devrez aussi confirmer (commit) les changements par :

git commit -m “Message”

Replace message with your actual commit message. Alternatively, you can do both things at once with: git commit -a -m “Message” The -a switch tells git to add and commit everything in the directory. As such, if you want to add only some files, you'll want to either create a .gitignore, or add the files separately using git add. Now that the repository is created and contains content, it's time to clone it to a new machine.

Remplacez « message » par votre vrai message de confirmation. Autre solution : vous pouvez faire les deux actions d'un coup avec :

git commit -a -m “Message”

Le commutateur -a indique à git de tout ajouter et confirmer tout ce qui se trouve dans le répertoire. Par conséquent, si vous voulez n'ajouter que quelques fichiers, soit vous créez un .gitignore, soit vous ajoutez les fichiers séparément avec la commande git add. Maintenant que le dépôt est créé et contient du contenu, il est temps de le cloner sur une nouvelle machine.

Cloning a git repository via ssh Assumptions: • You're using the normal ssh port (21) • Your username is gituser • The server's domain is git.example.com • The path is /home/gituser/git-repos • The repository itself is called cc-example.git Based on these assumptions, the git clone command would look like this: git clone ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git If you created the repository without the .git ending (or created a repository of an older directory), you'll just need to adapt the path to reflect this (so it would read “cc-example” at the end of our example). Assuming you haven't set up SSH with keyfiles, you'll be prompted to accept the fingerprint, and to enter your password.

Cloner un dépôt git via SSH

Hypothèses : * Vous utilisez le port normal ssh (21). * Votre identifiant est gituser. * Le domaine du serveur est git.example.com. * Le chemin est /home/gituser/git-repos. * Le dépôt lui-même s'appelle cc-example.git.

A partir de ces hypothèses, la commande de clonage de git devrait ressembler à ceci :

git clone ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git

Si vous créez votre dépôt sans .git à la fin (ou si vous le créez dans un ancien répertoire), vous aurez juste à adapter le chemin pour le refléter (ainsi ça donnerait « cc-example » à la fin de notre exemple). En supposant que vous n'avez pas paramétré SSH avec des fichiers de clés, vous aurez un pop-up pour vérifier votre empreinte ou pour entrer votre mot de passe.

The SSH format for git is as follows: ssh://<user>@<host>:[port]<absolute path> Replace <user> with the actual SSH username, <host> with the actual IP/Domain/Hostname, [port] with the port you're using (you can leave this out if you're using the standard port), and the <absolute path> must always be absolute – meaning it starts from the root filesystem directory: • Correct: /home/gituser/git-repos/cc-example.git • Wrong: ~/git-repos/cc-example.git, git-repos/cc-example.git, etc. If you're using the standard port, you can shorten the format a little by instead writing it like this: git clone <user>@<host>:<absolute path> However, it doesn't take much more effort to use the complete format, which may also help reduce errors when working with non-standard port values.

Le format SSH pour git est le suivant : ssh://<user>@<host>:[port]<absolute path>

Remplacez <user> par votre vrai identifiant SSH, <host> par la bonne valeur IP/domaine/nom d'hôte, [port] par le port que vous utilisez (vous pouvez faire l'impasse si vous utilisez le port standard) et <absolute path> doit toujours être absolu - ce qui veut dire qu'il commence toujours par le répertoire racine du système de fichiers. • Correct : /home/gituser/git-repos/cc-example.git. • Erronés : ~/git-repos/cc-example.git, git-repos/cc-example.git, etc.

Si vous utilisez le port standard, vous pouvez réduire un peu le format en écrivant la commande comme ceci :

git clone <user>@<host>:<absolute path>

Cependant, ça ne demande pas beaucoup plus d'effort d'utiliser le format complet, qui peut aussi aider à réduire le nombre d'erreurs si vous travaillez avec des valeurs de ports non standards.

Once you've cloned the repository, you can git add, git commit, and then (in order to synchronize the changes) use git push. The format of this command (like last month) is: git push <remote-target> <branch> Typically, the <remote-target> will be origin, and the <branch> will be master. So, a typical command could be: git push origin master

Une fois le dépôt cloné, vous pouvez faire git add, git commit et ensuite (de façon à synchroniser les changements) utilisez git push. Le format de cette commande (comme le mois dernier) est :

git push <remote-target> <branch>

Typiquement, <remote-target> sera l'origine et <branch> sera le maître. Aussi, une commande typique pourrait être :

git push origin master

If you run into an error (such as the remote origin not being defined), you'll need to add the target to your repository. To do this, change directory to the repository, and then run: git remote add origin ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git This will define a remote target called origin in the repository, and use the URL you supplied. This shouldn't typically be required (at least, in my testing I never needed to define a host like this). You can also use it to define multiple remote targets, in case you have various backup servers – though that could easily end up being very complex.

Si vous rencontrez une erreur (comme l'origine distante n'étant pas définie), vous devrez ajouter la cible à votre dépôt. Pour ce faire, changez de répertoire pour être dans votre dépôt et lancez :

git remote add origin ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git

Ceci définira une cible distante appelée origin dans le dépôt et utilisera l'URL que vous avez fournie. Ca ne devrait pas être exigé (du moins dans mes tests je n'ai jamais eu besoin de définir l'hôte de cette façon). Vous pouvez aussi l'utiliser pour définir de multiples cibles distantes, au cas où vous auriez plusieurs serveurs de sauvegarde, bien que cela puisse facilement devenir très compliqué.

Branches The reader who contacted me also wished for some information on creating, merging and cloning specific branches in a repository. Anyone planning to get into serious development with git will want to learn about branches, in order to keep the development snapshot separate from the stable. Creating a new branch Make sure your current working directory (cwd) is that of your repository, and then type the following command: git checkout -b <branch> This will create a new branch, called <branch>. It's technically short-hand for the following two commands: git branch <branch> git checkout <branch>

Branches

Le lecteur qui m'a contacté souhaitait aussi quelques informations sur la création, la fusion et clonage de branches particulières dans un dépôt. Toute personne qui envisage du développement sérieux avec git voudra apprendre ce que sont les branches, de façon à conserver l'image instantanée d'un développement séparé de la version stable.

Créer une nouvelle branche

Assurez-vous que le répertoire courant est celui de votre dépôt puis tapez la commande suivante :

git checkout -b <branch>

Une nouvelle branche sera créée, appelée <branch>. Techniquement, ce n'est que la contraction des deux commandes suivantes :

git branch <branch> git checkout <branch>

As you can see, the short-hand is a lot less repetition. These two steps are also required only if you're creating branches – changing between branches is as simple as writing: git checkout <branch> Once you've changed to the branch you want to work on, continue working as you normally would (edit files, add them, and commit them). However, there is an important change to the push step: git push origin <branch> To push your new branch to the remote host “origin”, you need to make sure you supply the correct branch name. Typically commands use master as a default value here, but that's true only if you're updating the master (i.e. stable) branch.

Comme vous pouvez le voir, la commande raccourcie évite les répétitions. Ces deux étapes ne sont requises que si vous créez des branches - passer d'une branche à l'autre est aussi simple que :

git checkout <branch>

Quand vous aurez changé pour la branche dans laquelle vous voulez travailler, continuez votre travail comme d'habitude (éditer des fichiers, en ajouter et les confirmer). Cependant il y a un gros changement pour l'étape du push :

git push origin <branch>

Pour pousser (push) la nouvelle branche vers l'hôte distant « origin », vous avez besoin de vous assurer que vous fournissez le bon nom de branche. Typiquement, les commandes utilisent ici maître comme valeur par défaut, mais ce n'est correct que si vous mettez à jour la branche maître (c'est-à-dire la branche stable).

Assuming you've completed development in the development branch, and are ready to merge it back into the stable (master) branch, then you would need to do the following: git checkout master This command switches you back to the stable branch – when merging you need to have checked out the target branch. Then merge the branches with: git merge <branch>

Supposons que vous avez terminé le développement dans la branche development et que vous êtes prêt à la fusionner dans la branche stable (le maître), alors vous utiliseriez la commande suivante :

git checkout master

Cette commande vous ramène dans la branche maître - quand vous fusionnez, il est nécessaire d'avoir vérifié la branche cible. Ensuite fusionnez les branches avec :

git merge <branch>

Make sure you enter the actual branch name. This type of merge uses the typical git approach to conflicts – if it can't automatically resolve the conflict, it will instead mark the changes in the file within the repository, and you need to resolve it manually, then re-add and commit the changes. See last month's article for more detail. If you typically develop in a linear way (i.e. the stable branch always points to an older point in the timeline, and the development branch is more recent), it shouldn't be an issue. However, if you have concurrent branches (i.e. you develop onwards normally after the most recent stable release, but also branch off into a mobile development from the same snapshot), it may cause some conflicts when merging.

Assurez-vous de saisir le nom de branche correct. Ce type de fusion utilise l'approche des conflits typique de git - si le conflit ne peut pas être résolu automatiquement, les écarts sont marqués dans le fichier dans le dépôt et vous devez l'analyser manuellement, puis ajouter à nouveau et confirmer les changements. Voir l'article du mois dernier pour plus de détails. Si vous développez normalement de façon linéaire (c'est-à-dire que la branche stable pointe toujours vers un point un plus ancien de l'échelle de temps et que la branche de développement est plus récente), il ne devrait pas y avoir de problème. Cependant, si vous avez des branches concurrentes ( disons que vous développez normalement à partir de la version publiée stable la plus récente, mais qu'à partir de la même image vous avez une branche pour un développement pour le mobile), il peut y avoir quelques conflits au moment de la fusion.

Deleting a branch Deleting an old branch locally is as simple as running: git branch -D <branch> However, if you want to remove it from the remote host as well, you'll need to do one of the following: git push origin :<branch> git push origin –delete <branch> The difference is that the top command is supported in versions of git as of 1.5.0, and the second one is supported only as of 1.7.0.

Supprimer une branche

Localement une vieille branche s'efface aussi simplement que :

git branch -D <branch>

Cependant, si vous voulez aussi l'effacer sur l'hôte distant, vous devrez faire l'une des commandes suivantes :

git push origin :<branch>

git push origin –delete <branch>

La différence vient de ce que la commande du haut est supportée dans les versions de git dès la 1.5.0 et que la seconde est supportée uniquement à partir de la 1.7.0.

Renaming a branch If you want to rename a branch locally (i.e. from development to dev): git branch -m <old> <new> So, in the example: git branch -m development dev Also, if you want to rename the current branch, you can omit the <old> part of the command, i.e. git branch -m dev.

Renommer une branche

Si vous voulez renommer une branche localement (par exemple de development à dev) :

git branch -m <old> <new>

Ainsi, pour notre exemple :

git branch -m development dev

Si vous voulez renommer la branche courante, vous pouvez omettre <old> dans la commande, par exemple git branch -m dev.

Renaming a local branch when pushing it to the remote server Say, for example, you have a branch called testing on your copy of the repository. Problem is – someone beat you to it and created a branch called testing with different changes from your own. You could, naturally, rename your branch first, and then push it. Or else tell the remote target what to rename the branch to when pushing it with the following command: git push origin <local>:<remote> So, in our example: git push origin testing:mobile

Renommer une branche locale avant de la pousser vers le serveur distant

Disons, par exemple, que vous avez une branche appelée testing sur votre copie du dépôt. Problème : quelqu'un vous a coupé l'herbe sous le pied et a créé une branche nommée testing avec plusieurs changements par rapport à la vôtre. Vous pouvez bien sûr renommer localement votre branche, puis la pousser. Autrement, au moment de pousser la branche vers la cible distante, indiquez-lui comment la renommer par la commande :

git push origin <local>:<remote>

Ce qui donne dans notre exemple :

git push origin testing:mobile

This will take our local testing repository and upload it to the server, while renaming that branch mobile. This may also help people to understand the deletion command in git 1.5.0: you're essentially pushing a NULL repository (i.e. one that doesn't exist) to the remote branch, which deletes it. Checking out a specific branch This was the last question posed in the email I received. I assumed he meant literally cloning a single branch and ignoring all the rest. This is a slightly more complicated task, and it is outlined below: mkdir <folder> cd <folder> git –bare init

Notre dépôt testing va être pris et téléversé sur le serveur, avec le nom de branche mobile. Ceci aide peut-être à comprendre la commande de suppression dans git 1.5.0 : en fait, vous poussez un dépôt « null » (c'est-à-dire un qui n'existe pas) vers la branche distante, ce qui l'efface.

Vérifier une branche spécifique

C'est la dernière question du mail que j'ai reçu. J'ai supposé qu'il voulait dire cloner une seule branche et ignorer tout le reste. C'est une tâche un peu plus compliquée que je vais décrire ci-dessous :

mkdir <folder>

cd <folder>

git –bare init

Alternatively, just run git –bare init <folder> git remote add origin ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git This is required in order to link the remote repository with the new local repository you just created, that will end up containing only the branch you want. git fetch origin <branch>:refs/remotes/origin/<branch>

Ou d'une autre façon, lancez simplement git –bare init <folder>

git remote add origin ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git

Ceci est nécessaire pour relier le dépôt distant au nouveau dépôt local que vous venez de créer, qui ne contiendra que la branche que vous voulez.

git fetch origin <branch>:refs/remotes/origin/<branch>

There are a few things to note about this command: If your remote target is something other than origin, change both occurrences of origin in the command. Also, replace <branch> with the name of the branch. Do not change the part that reads “/refs/remotes/”. This essentially prepares the download of the specific branch you want from the repository. git checkout -b <branch> –track origin/<branch> This now creates the branch in your local repository, and then links it with the branch from the remote target – effectively creating a repository containing only that branch. Note: If you don't mind downloading all the existing branches, and simply want git to default to a different branch (i.e. if you plan to merge branches later), you can do it much easier with: git clone ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git -b <branch>

Il y a quelques points à noter à propos de cette commande : si votre cible distante est différente d'origin, modifiez les deux occurrences d'origin dans la commande. De même, remplacez <branch> par le nom de la branche. Ne changez pas la partie « /refs/remote/ ». Ceci est important pour préparer le téléchargement de la branche spécifique que vous voulez à partir du dépôt.

git checkout -b <branch> –track origin/<branch>

Ceci crée maintenant la branche dans votre dépôt local et ensuite la relie à la branche de la cible distante - en fait un dépôt ne contenant que cette branche est créé.

Note : Si cela ne vous dérange pas de télécharger toutes les branches existantes et que vous souhaitez seulement que git pointe par défaut vers une autre branche (par exemple si vous prévoyez de fusionner des branches plus tard), vous pouvez le faire beaucoup plus simplement avec :

git clone ssh://gituser@git.example.com:21/home/gituser/git-repos/cc-example.git -b <branch>

This clones the repository as normal (including all branches), and then switches the default branch (i.e. master) to the branch you specify (i.e. testing). This would generally be my preference, as opposed to the complicated series of steps listed above. Most likely you'll eventually need access to at least some of the other branches, and this makes it relatively painless to switch between them. Hopefully this has helped explain some of the intricacies of managing git branches and servers. If you have any follow-up questions, or ran into any issues with the examples in the article, feel free to email me at lswest34+fcm@gmail.com. You're also very welcome to email me with requests for articles, or if you want to offer your 2 cents on any of the steps outlined here.

Avec cette commande, le dépôt est cloné normalement (avec toutes ses branches) et il commute ensuite de la branche par défaut (c'est-à-dire le maître) vers la branche que vous spécifiez (par exemple testing). Ceci aurait généralement ma préférence, par rapport à la série compliquée d'étapes listées plus haut. Probablement, vous aurez besoin d'un éventuel accès à quelques-unes des autres branches et ça permet une commutation sans peine de l'une à l'autre.

J'espère que cet article vous a aidé à comprendre quelques subtilités de la gestion des branches et des serveurs git. Si vous avez la moindre question de suivi, ou si vous avez des problèmes en utilisant les exemples de cet article, n'hésitez pas à m'envoyer un mail à lswest34+fcm@gmail.com. Merci de bien vouloir m'envoyer des suggestions d'articles par mail ou si vous voulez ajouter votre grain de sel sur les étapes décrites ici.

issue86/command_conquer.txt · Dernière modification : 2014/12/27 10:17 de andre_domenech