Учебник - Создание первого изменения

(Это страница 4 из 9 серии [:Tutorial:учебников]. Предыдущая часть - [:RussianTutorialHistory], следующая часть [:RussianTutorialShareChange])

Начав с RussianTutorialHistory, теперь мы внутри репозитория my-hello, склонированного в RussianTutorialClone.

При работе с Mercurial рекомендуется изолировать связанные изменения в раздельном [:Repository:репозитории] (смотри [:WorkingPractices:Лучшие практики]). Это предотвращает смешивание независимого кода и упрощает тестирование персональных частей работы отдельно друг от друга. Давайте начнём следуя этой рекомендации.

Наша цель проста - заставить программу "hello, world" ("Привет, мир") выводить другую строчку. Для начала мы создаем новый репозитарий my-hello-new-output [:Clone:клонированием] my-hello для нашего небольшого проекта (используем Mercurial 1.0):

$ hg clone my-hello my-hello-new-output
updating working directory
2 files updated, 0 files merged, 0 files removed, 0 files unresolved

Заметьте что мы дали нашему новому репозитарию имя описывающее его назначение. Сделать клон репозитария в Mercurial это "дешевая" операция. Мы быстро накопим много слегка оличающихся репозитариев. Если мы не будем давать репозитариям описательных имён, то вскоре потеряем возможность оличить один от друго (see RepositoryNaming).

Пора внести изменения в новый репозиторий. Перейдём в [:WorkingDirectory:рабочий каталог] репозитория и отредактируем исходник нашим любимым редактором:

$ cd my-hello-new-output
$ vi hello.c

Первоначальное содержимое hello.c выглядело так:

Toggle line numbers
/*
 * hello.c
 *
 * Placed in the public domain by Bryan O'Sullivan
 *
 * This program is not covered by patents in the United States or other
 * countries.
 */

#include <stdio.h>

int main(int argc, char **argv)
{
        printf("hello, world!\n");
        return 0;
}

Отредактируем функцию main. Теперь она выводит еще одну строку:

Toggle line numbers
(...)

int main(int argc, char **argv)
{
        printf("hello, world!\n");
        printf("sure am glad I'm using Mercurial!\n");
        return 0;
}

Сделав это, выходим из редактора. Вот и готово. Можно содавать [:ChangeSet:changeset].

Но что если мы отвлеклись и забыли какие изменения мы собирались внести в changeset? В таком случае мы воспользуемся командой status.

$ hg status
M hello.c

Вывод краток, но префикс M говорит нам что hello.c был модифицирован, и наши исправления готовы войти в changeset.

Вместо скучного hg status мы можем вводить hg st. Mercurial позволяет сокращать команды пока введённые символы не двусмысленны.

$ hg st
M hello.c

Мы также можем просмотреть реальные изменения в файлах используя команду diff:

$ hg diff
diff -r 82e55d328c8c hello.c
--- a/hello.c   Fri Aug 26 01:21:28 2005 -0700
+++ b/hello.c   Mon May 05 00:27:56 2008 +0200
@@ -12,5 +12,6 @@
 int main(int argc, char **argv)
 {
        printf("hello, world!\n");
+       printf("sure am glad I'm using Mercurial!\n");
        return 0;
 }

<!> Если мы хотим отменить наши изменения и начать заново, мы можем использовать команду revert для восстановления hello.c в немодифицированное состояние (или использовать опцию --all что бы откатить все файлы). Только убедитесь что знаете чего хотите (см. [:Revert]).

$ hg revert hello.c

revert переименует модифицированный файл hello.c в hello.c.orig и восстановит hello.c в немодифицированное состояние.

status now lists hello.c.orig as not tracked (prefix "?").

$ hg st
? hello.c.orig

Если мы снова передумали и хотим использовать наши отменённые изменения, мы просто удаляем немодифицированный hello.c и переименовываем модифицированный hello.c.orig в hello.c

$ rm hello.c
$ mv hello.c.orig hello.c
$ hg st
M hello.c

The act of creating a changeset is called [:Commit:committing] it. We perform a commit using the commit command. The commit command has a nice short alias: ci ("check in"), so we can use that:

$ hg ci

This drops us into an editor, and presents us with a few cryptic lines of text.

Note: The default editor is vi. This can be changed using the EDITOR or [:HGEDITOR] environment variables.

HG: Enter commit message.  Lines beginning with 'HG:' are removed.
HG: --
HG: user: mpm@selenic.com
HG: branch 'default'
HG: changed hello.c

The first line is empty and the lines that follow identify the user, branch name and the files that will go into this changeset.

The default branch name is "default" (see NamedBranches). The default value for "user" is taken from the ~/.hgrc configuration file from value "username" of section "ui" (see [http://www.selenic.com/mercurial/hgrc.5.html#ui hgrc(5)]). Alternatively, it can also be specified on the command line with option -u (see hg help ci or [http://www.selenic.com/mercurial/hg.1.html#commit hg.1.html#commit]).

To commit the changeset, we must describe the reason for it (see [:ChangeSetComments]). Let's type something like this:

Express great joy at existence of Mercurial
HG: Enter commit message.  Lines beginning with 'HG:' are removed.
HG: --
HG: user: mpm@selenic.com
HG: branch 'default'
HG: changed hello.c

Next, we save the text and quit the editor, and, if all goes well, the commit command will exit and prints no output.

<!> If you quit the editor without saving the text or enter no text, commit will abort the operation, so you may change your mind before committing.

Let's see what the status command will tell us now?

$ hg st

Nothing! Our change has been committed to a changeset, so there's no modified file in need of a commit. Our [:Tip:tip] now matches our working directory contents.

The [:Parent:parents] command shows us that our repository's working directory is now synced (see [:Update]) to the newly committed changeset (here we have only one parent revision, which is always the case after a commit. We will see two parents in TutorialMerge):

$ hg par
changeset:   2:86794f718fb1
tag:         tip
user:        mpm@selenic.com
date:        Mon May 05 01:20:46 2008 +0200
summary:     Express great joy at existence of Mercurial

There it is! We've committed a new changeset.

We can now examine the change history for our new work:

$ hg log
changeset:   2:86794f718fb1
tag:         tip
user:        mpm@selenic.com
date:        Mon May 05 01:20:46 2008 +0200
summary:     Express great joy at existence of Mercurial

(...)

Note: The user, date, and [:ChangeSetID:changeset ID] will of course vary.

As we discussed in [:RussianTutorialClone], the new changeset only exists in this repository. This is a critical part of the way Mercurial works.

Как сделать изменения доступными другим пользователям, рассказано в RussianTutorialShareChange.


CategoryTutorial CategoryRussian