Knzsoft разработка по, консультации, учебные материалы

Basic Work Cycle¶

  • Update your working copy — For this you use the command
  • Make changes — For this you may edit files in an editor, or use the , , , commands
  • Review Changes — For this you use the and
  • Fix Mistakes — Make additional edits to files or you can use the to restore files or directories to an unmodified state
  • Resolve Conflicts — There is a chance others have committed changes while you have been changing your working copy. You should run the command to bring your copy up to date. This may create a local conflict where someone may have added a file with a name that you also want to add, or may have made changes to the same line of a file as you. For this use the command.
  • Publish Changes — For this you use the command

Adding a File

After creating the file «test-file.txt» in the working copy.

$ svn status
?       test-file.txt

? indicates test-file.txt is not under version control

$ svn add test-file.txt
A         test-file.txt

$ svn status
A       test-file.txt

«A» indicates file is scheduled for addition

Running a diff

$ svn diff
Index test-file.txt
===================================================================
--- test-file.txt   (revision 0)
+++ test-file.txt   (revision 0)
@@ -0,0 +1 @@
+This is a test file for svn-basics.

Property changes on test-file.txt
___________________________________________________________________
Added svneol-style
   + native

Committing a file

$ svn commit test-file.txt -m "added test-file.txt"
Adding         test-file.txt
Transmitting file data .
Committed revision 2.

Update the working copy

$ svn update
U    test-file.txt
Updated to revision 3.

«U» indicates an «Update» to a file or directory

Modify the file (this example uses the vim editor)

$ vim test-file.txt

Check the Status

$ svn status
M       test-file.txt

«M» indicates the file has been «Modified»

$ svn diff
Index test-file.txt
===================================================================
--- test-file.txt   (revision 3)
+++ test-file.txt   (working copy)
@@ -1,2 +1,3 @@
 This is a test file for svn-basics.
 This is a new line added by someone else.
+This line added by me.

Resolving Conflicts

Suppose someone edits the same line as you before you commit

$ svn update
Conflict discovered in 'test-file.txt'.
Select (p) postpone, (df) diff-full, (e) edit,
        (mc) mine-conflict, (tc) theirs-conflict,
        (s) show all options

This is just like if you had ran the command

Selecting displays this:

--- .svn/text-base/test-file.txt.svn-base   Sun Jul 17 17:38:52 2011
+++ .svn/tmp/test-file.txt.tmp  Sun Jul 17 21:35:09 2011
@@ -1,2 +1,7 @@
 This is a test file for svn-basics.
 This is a new line added by someone else.
+<<<<<<< .mine
+This line added by me.
+=======
+This line is added by someone else also.
+>>>>>>> .r4
Select: (p) postpone, (df) diff-full, (e) edit, (r) resolved,
        (mc) mine-conflict, (tc) theirs-conflict,
        (s) show all options:

If you choose , Subversion will launch an editor with both sets of changes included for you to edit. You can save your changes in the editor and then select (for resolved).

G    test-file.txt
Updated to revision 4.

«G» indicates «merGed»

Собираем свой flow для git с нуля

Ее основными тезисами были:

GitFlow противоречит тезису «ветки должны быть короткоживущими».
Это важно, потому что чем меньше живет ветка — тем меньше шанс конфликтов (не только git, но и логических)
GitFlow препятствует rebase-ам, чтобы сохранить merge-коммиты.
Да, их можно сохранять и при ребейзах, но команды Git Flow не делают этого.
GitFlow отрицает подход Contunious Delivery, считая, что каждый акт Delivery должен совершаться релиз-инженером, да и в целом можно увидеть, что он ориентирован только на долгий релизный цикл.
GitFlow не дружит с микросервисами поверх мультирепозиториев (впрочем, тут вообще мало что подходит, это идея, которая всегда плохо заканчивается)

Но проблема GitFlow в том, что он и с монорепозиториями тоже не дружит. Я сам об это споткнулся в процессе дизайна пайплайнов CI: GitFlow чудовищно мешает, когда работает поверх монорепозитория с несколькими deliverables, например, когда в одном репозитории отдельно и бэкэнд, и фронтэнд — уже из-за того, что он позволяет докоммичивать в релизные ветки, могут возникнуть конфликты при обратном мердже, если в один момент времени существует больше, чем одна релизная ветка

Да даже если одна, все равно плохо — в таких условиях надо патчить в принципе релизные механизмы GitFlow, чтобы хоть как-то заработали отдельные релизы сущностей.

Access via custom protocol with SSH encryption (svn+ssh://)

It is not necessary to run the SVN server (svnserve) in order to access SVN repositories on a remote machine using this method. However, it is assumed that the SSH server is running in the remote machine with the repository and it is allowing incoming connections. To confirm, please try to login to that machine using ssh. If you can login, then everything is perfect. If you cannot login, please address it before continuing further.

The svn+ssh:// protocol is used for accessing SVN repositories with SSH based encryption for secure data transfer. To access a repository using this method, run the following command:

  $ svn co svn+ssh://hostname/home/svn/myproject myproject --username user_name

NOTE: You must use full path (/home/svn/myproject) to access an SVN repository using this method.

Based on the SSH server configuration, it prompts for password. You must enter the password you use to login via ssh. Once it is authenticated, it checks out the code from SVN repository.

You can also refer the SVN book for details about the svn+ssh:// protocol.

История

В 2000 году компанией CollabNet была создана Subversion, предназначенная для написания системы управления версиями с открытым исходным кодом. Она работал также, как и CVS, но исправляла ошибки и предоставляла некоторые функции, отсутствующие в CVS. К 2001 году Subversion продвинулась достаточно далеко, чтобы разместить свой собственный исходный код. Через год Subversion уже использовалась десятками частных разработчиков и магазинов для реальной работы. После этого прошло еще два года, в течение которых происходило исправление ошибок и стабилизация, пока в феврале 2004 года не была выпущена версия 1.0. В ноябре 2009 года Subversion была принята в Apache Incubator: это ознаменовало начало процесса становления проекта Apache как продукта высшего уровня. Subversion стала проектом Apache высшего уровня 17 февраля 2010 году..

Версия Последняя версия Дата выпуска Статус
Версия 1.0 1.0.9 2004-10-13 Больше не поддерживается
Версия 1.1 1.1.4 2005-04-01 Больше не поддерживается
Версия 1.2 1.2.3 2005-08-19 Больше не поддерживается
Версия 1.3 1.3.2 2006-05-23 Больше не поддерживается
Версия 1.4 1.4.6 2007-12-21 Больше не поддерживается
Версия 1.5 1.5.9 2010-12-06 Больше не поддерживается
Версия 1.6 1.6.23 2013-05-30 Больше не поддерживается
Версия 1.7 1.7.22 2015-08-12 Больше не поддерживается
Версия 1.8 1.8.19 2017-10-8 Частично поддерживается
Версия 1.9 1.9.10 2016-11-29 Полностью поддерживается
Версия 1.10 1.10.4 2019-01-11 Полностью поддерживается
Версия 1.11 1.11.1 2019-01-11 Полностью поддерживается
Версия 1.12.0 1.12.0 2019-04-24 Полностью поддерживается

Как не выстрелить себе в ногу, используя Liquibase

Никогда не было, и вот опять!

На очередном проекте мы решили использовать Liquibase с самого начала, чтобы избежать проблем в будущем. Как оказалось, не все молодые члены команды умеют его правильно использовать. Я провёл внутренний воркшоп, который затем решил превратить в статью.

Статья включает в себя полезные советы и описание трех самых явных ловушек, в которые можно попасть, работая с инструментами миграции реляционных баз данных, в частности Liquibase. Рассчитана на Java разработчиков уровня Junior и Middle, для более опытных разработчиков может быть интересна для структуризации и повторения того, что, скорее всего, уже известно.

Committing Changes¶

Only Committers can commit directly to the repository. The following example shows using your Apache ID and password.

$ svn commit test-file.c --username your-name --password your-password \
  -m "added new C file"
Sending        test-file.txt
Transmitting file data .
Committed revision 5.

In general, you may not have to include always your username or password if you do a proper setup of your ssh key or have subversion store the password.

Always check your changes with «svn diff» and «svn status». Also be careful to specify the files and/or directories you want to change, if
you don’t specify, SVN will commit all your changes.

For further information see the Basic Work Cycle page from Subversion Book.

Merging changes to a branch¶

New development is done in the «trunk», development area, of the tree. Stable, release branches, are specifically named and can be found
in the branches area of the openoffice svn tree. With few exceptions you do NOT do direct commits to the stable, release,
branches. Changes, commits, to stable branch are typically only done during a formal release cycle and must be discussed on the «dev» list.

When a new release is in preparation, bug fixes are reviewed, and fixes that have been made to «trunk» get applied to the stable, release, branch. This is done using the «svn merge» command which finds previous changes and replays them. SVN also keeps a record
of the specific commits that have been merged so the changes are much easier to track down.

The first step is to do a check out of the stable, release, branch. The following examples use the AOO34 release branch, and assume
you want to apply changes from trunk for a new release, maybe AOO341.

You can do a complete checkout of the release branch or you can save some space by using the «—depth=empty» option:

 % svn co --depth=empty https://svn.apache.org/repos/asf/openoffice/branches/AOO34 aoo-stable
 U   aoo-stable
 Checked out revision 1347362.

This will put a placeholder branch for the AOO34 in directory «aoo-stable».

In the aoo-stable directory, you can keep saving space (rather convenient) until you reach the directory where you want to make changes:

 % svn up --depth=empty main
 Updating 'main'
 A    main
 Updated to revision 1347363.
 % svn up --depth=empty jvmfwk
 Updating 'jvmfwk'
 A    jvmfwk
 Updated to revision 1347366.

At this point, there are svn placeholder entries for /main/jvmfwk.

To do a complete checkout from there:

 svn up --set-depth=infinity
 Updating '.'
 A    source
 A    sourceelements.hxx
 A    sourcefwkbase.cxx
 ... (and so on)

Now merge the specific revision(s) you want (in this case r1333165):

 svn merge -c1333165 https//svn.apache.orgreposasfopenofficetrunkmainjvmfwk .
 --- Merging r1333165 into '.'
 U    distributionsOpenOfficeorgjavavendors_unx.xml

At this point, you have merged r1333165 into r1347366. (For release from trunk to a new release, it’s likely you would be merging a higher revision to a lower existing release revision.)

After you finish merging, check your changes with «svn status» and «svn diff»
and commit from the aoo-update directory:

 svn commit -m "Merge r1329539, r1329547, 1333165 - Add Oracle as a Java vendor on unix." distributionsOpenOfficeorgjavavendors_unx.xml distributionsOpenOfficeorgjavavendors_freebsd.xml
 Sending        distributionsOpenOfficeorgjavavendors_freebsd.xml
 Sending        distributionsOpenOfficeorgjavavendors_unx.xml
 Transmitting file data ..
 Committed revision 1347377.

Ветвление и метки

Subversion использует модель межфайлового разветвления из системы контроля версий Perforce. Ветвь является самостоятельной версией разработки, независимой от других. Метка связана с маркировкой репозитория в определенный момент времени, что позволяет легко найти её в будущем. Единственное различие между ветвями и метками в Subversion это способ их использования. Новая ветвь или метка устанавливаются с помощью команды «svn copy», которая должна использоваться вместо механизма собственной операционной системы. Скопированный каталог связан с оригинальным в репозитории для сохранения его истории, а копия занимает очень мало места в репозитории. Все версии в каждой из ветвей сохраняют историю файла до точки копии, а также любые изменения, внесенные с этого момента. Можно «слить» изменения обратно в ствол или между ветвями.

Рис. 1. Пример эволюции ветвей в Subversion

Настройка SVN Авторизации по пути (Path-Based Authorization)

Разделяем пользователей на группы:Внимание! Комментарии в файле не допускаются, поэтому не забудьте их удалить!


admins = oleg        // группа администраторы, запишем oleg      
devteam = ira, oleg  // группа разработчиков главного проекта
editors = @devteam, sveta  // пользователи пишущие документацию
// ранее описанные группы пользователей можно включить в последующие,
// при ссылке на группу используется @имя_группы

Укажем, кто может просматривать листинг имеющихся хранилищ.

[/]
* = r
@admins = rw

Доступ к хранилищу RepA.olegira


oleg =                // отнимаем все права доступа, пустое значение
ira = rw              // чтение, запись

Доступ к хранилищу RepB.iraoleg


ira =
oleg = rw

Доступ к хранилищу документов.editors


@editors = rw

В итоге получим файл настроек для авторизации svnaccess.


admins = oleg
devteam = ira, oleg
editors = @devteam, sveta

[/]
* = r
@admins = rw


oleg =
ira = r


ira =
oleg = r


@editors = rw
anonymous = r

svnaccessC:\usr\local\Apache2\conf\svn\Перезапустите сервер Apachehttp://localhost/svn/C:\usr\local\Apache2\conf\svn\svnpasswdstore1, store2

Далее к: Часть 3 — Trac …

Create SVN Repository

There are several typical places to put a Subversion repository; most common places are: /srv/svn, /usr/local/svn and /home/svn. For clarity’s sake, we’ll assume we are putting the Subversion repository in /home/svn, and your project’s name is simply ‘myproject’

There are also several common ways to set permissions on your repository. However, this area is the most common source of errors in installation, so we will cover it thoroughly. Typically, you should choose to create a new group called ‘subversion’ that will own the repository directory. To do this (see AddUsersHowto for details):

  1. Choose System > Administration > Users and Groups from your Ubuntu menu.

  2. Click the ‘Manage Groups’ button.
  3. Click the ‘Add’ button.
  4. Name the group ‘subversion’
  5. Add yourself and www-data (the Apache user) as users to this group

    (Note: in order to see www-data you may need to see FixShowAllUsers)

  6. Click ‘OK’, then click ‘Close’ twice to commit your changes and exit the app.

You have to logout and login again before you are a member of the subversion group, and can do check ins.

Now issue the following commands:

   $ sudo mkdir /home/svn
   $ cd /home/svn
   $ sudo mkdir myproject

The SVN repository can be created using the following command:

  $ sudo svnadmin create /home/svn/myproject

And use the following commands to correct file permissions:

   $ cd /home/svn
   $ sudo chown -R www-data:subversion myproject
   $ sudo chmod -R g+rws myproject

The last command sets gid for proper permissions on all new files added to your Subversion repository.

If you want to use WebDAV as an access method described below, repeat the chmod -R g+rws myproject command again. This is because svnadmin will create directories and files without group write access. This is no problem for read only access or using the custom svn protocol but when Apache tries to commit changes to the repository linux will deny it access. Also the owner and group are set as root. This can be changed by repeating the chown and chgrp commands listed above.

Access Methods

Subversion repositories can be accessed (checkout) through many different methods-on local disk, or through various network protocols. A repository location, however, is always a URL. The table describes how different URL schemas map to the available access methods.

Schema

Access Method

file:///

direct repository access (on local disk)

http://

Access via WebDAV protocol to Subversion-aware Apache 2 web server

https://

Same as http://, but with SSL encryption

svn://

Access via custom protocol to an svnserve server

svn+ssh://

Same as svn://, but through an SSH tunnel

In this section, we will see how to configure SVN for all these access methods. Here, we cover the basics. For more advanced usage details, you are always recommended to refer the svn book.

Sub-commands and Abbreviations¶

Subversion commands can be run from a command shell such as Bash on Linux. The subversion client command is followed by optional sub-commands, options, and arguments.

Show the program version and modules

$ svn --version

Run a sub-command

$ svn <subcommand> options args

Most sub-commands take file and/or directory arguments, recursing on the directories. If no arguments are supplied to such a command, it recurses on the current directory (inclusive) by default. (from )

The following is only a partial list of sub-commands relating to this instruction. For a complete list, see the Subversion Book, or use .

  • — Schedule a new file or directory (including contained files) for inclusion in the repository
  • , — Create a local working copy of a remote repository
  • , — Commit (check in) local changes to the repository
  • , — Copy one or more files in a working copy or in the repository
  • , , , — Items specified are scheduled for deletion upon the next commit. Working copy files not yet committed are deleted immediately.
  • , — Displays differences in files from the directory
  • , , — Subversion help and help on sub-commands
  • , , , — Moves files or directories in your working copy or repository
  • — Resolve conflicts on working copy files or directories
  • — Undo all local edits or optionally a file or directory
  • — Print the status of working copy files and directories
  • — Bring changes from the repository into your working copy

Файловая система

Файловую систему Subversion можно рассматривать как «двумерную». Для однозначного обращения к элементам файловой системы используются два элемента:

  • Путь (обычный путь файловой системы);
  • Проверка (ревизия).

Каждая проверка в файловой системе Subversion имеет свой собственный root, который используется для доступа к содержимому в этой проверке. Файлы хранятся в виде ссылок на самые последние изменения; Таким образом, хранилище Subversion довольно компактное. Система потребляет пространство памяти, пропорциональное количеству внесенных изменений, а не количеству проверок.
Файловая система Subversion использует транзакции, чтобы сохранить изменения атомарными. Транзакция работает с указанной версией файловой системы, но не обязательно последней. У транзакции есть свой собственный рут, на котором совершаются изменения. Это либо фиксируется, либо становится последней версией, либо прерывается. Транзакция на самом деле является долгоживущим файловым объектом; клиенту не нужно совершать или отменять транзакцию самостоятельно, он может также начать транзакцию, выйти и затем снова открыть транзакцию и продолжить ее использование. Потенциально, несколько клиентов могут получить доступ к одной и той же транзакции и работать вместе при атомарном изменении, хотя существующие клиенты не предоставляют эту возможность.

Подключаем SVN к Apache

  1. Скопируйте из каталога C:\usr\local\Subversion\bin\ в каталог C:\usr\local\Apache2\modules\ все файлы *.so, *.dll
    • intl3_svn.dll
    • libapr.dll
    • ssleay32.dll
    • mod_authz_svn.so
    • mod_dav_svn.so

Настройка:

  1. создайте каталог C:\usr\local\Apache2\conf\svn\ и создайте в нем файл httpd-svn.conf со следующим содержанием:
    	# httpd-svn.conf SVN Config file
    	#
    	# Подключаем модули для работы с SVN
            LoadModule dav_module         modules/mod_dav.so
    	LoadModule dav_svn_module     modules/mod_dav_svn.so
    	LoadModule authz_svn_module 	modules/mod_authz_svn.so
    	
    	<Location /svn>
    	DAV svn
    	# Абсолютный путь к каталогу содержащему SVN хранилища
      	SVNParentPath "D:/repos"
    	# выводит список хранилищ
    	SVNListParentPath on
    	# файл оформления списка хранилищ
    	SVNIndexXSLT "/svnindex.xsl"
    
      	# файл ACL разграничения доступа к хранилищам
    	# раскоментируйте для использования
      	AuthzSVNAccessFile conf/svn/svnaccess
    
      	# только аутентифицированные пользователи получат доступ к хранилищу
      	Require valid-user
    
      	# Тип аутентификации
      	AuthType Basic
    	# Общее название хранилища
      	AuthName "My SVN Repository"
    	# Файл с паролями пользователей для доступа в SVN хранилище
      	AuthUserFile conf/svn/svnpasswd
    
    	</Location>
    	
  2. перейдите в каталог C:\usr\local\Apache2\conf\
  3. откройте файл httpd.conf и добавьте следующие строки в конец файла:
    	# Subversion system
    	include conf/svn/httpd-svn.conf
    	
  4. сохраните файл и закройте его.

C:\usr\local\Apache2\htdocs\

  • svnindex.xsl
  • svnindex.css
  • menucheckout.ico

Для доступа введите имя guest и оставьте пароль пустым.

Создание файла паролей svnpasswd

Первый способ — используем скрипт svnuser.bat

  1. Откройте блокнот и скопируйте следующий код
    @echo off
    if %1=="" goto USAGE
    
    if not exist svnpasswd htpasswd -cm svnpasswd %1
    if exist svnpasswd htpasswd -m svnpasswd %1
    goto EXIT
    
    :USAGE
    echo Create SVN access file
    echo Usage: svnuser username 
    
    :EXIT
    
  2. Сохраните файл с именем
    svnuser.bat

    в каталог C:\usr\local\Apache2\bin\

  3. запустите командную строку и перейдите в каталог C:\usr\local\Apache2\bin\
  4. добавьте пользователей по очереди с помощью команды
    svnuser имя

    , программа запросит пароль — введите его.

  5. в каталоге C:\usr\local\Apache2\bin\ вы найдете созданный файл с паролями svnpasswd
  6. скопируйте файл в каталог C:\usr\local\Apache2\conf\svn\

Второй способ — вручную

  1. Откройте командную строку
  2. перейдите в каталог C:\usr\local\Apache2\bin\
  3. чтобы добавить пользователей имеющих право доступа к хранилищу, выполните для каждого пользователя команду
    htpasswd svnpasswd user1 passwd_for_user1
  4. в каталоге C:\usr\local\Apache2\bin\ вы найдете созданный файл с паролями svnpasswd
  5. скопируйте файл в каталог C:\usr\local\Apache2\conf\svn\

Примечание

Direct repository access (file://)

This is the simplest of all access methods. It does not require any SVN server process to be running. This access method is used to access SVN from the same machine. The syntax is as follows:

  $ svn co file:///home/svn/myproject
            or
  $ svn co file://localhost/home/svn/myproject

NOTE: Please note, if you do not specify the hostname, you must use three forward slashes (///). If you specify the hostname, you must use two forward slashes (//).

The repository permission is dependant on filesystem permission. If the user has read/write permission, he can checkout/commit the changes to the repository. If you set permissions as above, you can give new users the ability to checkout/commit by simply adding them to the Subversion group you added above.

Access via custom protocol (svn://)

Once the SVN repository is created, you can configure the access control. You can edit /home/svn/myproject/conf/svnserve.conf file to configure the access control.

NOTE: svnserve.conf is sensitive to whitespace, be sure not to leave any whitespace at the start of a line or it will not be able to read the file.

For example, to setup authentication you can uncomment the following lines in the configuration file:

  # 
  # password-db = passwd

After uncommenting the above lines, you can maintain the user list in passwd file. So, edit the file passwd in the same directory and add new user. The syntax is as follows:

  username = password

For more details, please refer the file.

Now, to access SVN via svn:// custom protocol either from the same machine or different machine, you can run svnserver using svnserve command. The syntax is as follows:

  $ svnserve -d --foreground -r /home/svn
    # -d -- daemon mode
    # --foreground -- run in foreground (useful for debugging)
    # -r -- root of directory to serve

  For more usage details, please refer,
  $ svnserve --help

Once you run this command, SVN starts listening on default port (3690). To access the project repository, you must run the following command:

  $ svn co svn://hostname/myproject myproject --username user_name

Based on server configuration, it prompts for password. Once it is authenticated, it checks out the code from SVN repository.

To synchronize the project repository with the local copy, you can run update sub-command. The syntax is as follows:

  $ cd project_dir
  $ svn update

For more details about using each SVN sub-command, you can refer the manual. For example, to learn more about co (checkout) command, please run:

  $ svn help co

Start svnserve at bootup

One can start the svnserve daemon at bootup using an initd script. Look at Michał Wojciechowski Blog post for instructions and a good initd script for svnserve.

Start svnserve at bootup using upstart

On recent upstart based Ubuntu versions you can place an upstart config file in /etc/init/svnserve.conf. See the example svnserve.conf; however, you will most likely need to edit it after reading the upstart documentation and the svnserve man page.

After placing the config file you can start svnserve with:

  $ sudo initctl start svnserve

Start svnserve at bootup using xinetd

An alternative method to run svnserve at startup is to install xinetd, and then add the following line to /etc/xinetd.conf (replacing ‘svnowner’ and ‘/home/svn’ with appropriate values)

svn stream tcp nowait svnowner /usr/bin/svnserve svnserve -i -r /home/svn

Ansible против Puppet

Перевод

Ansible и Puppet представляют собой системы управления конфигурациями (SCM), необходимые для построения повторяющихся инфраструктур.
Ansible отличается простотой использования, имеет безагентную архитектуру (не требует установки агента/клиента на целевую систему) и YAML-подобный DSL, написана на Python и легко расширяется за счет модулей. Обычно управляет конфигурацией Linux.
Puppet имеет клиент-серверную архитектуру (периодически опрашивает сервер, чтобы внести в конфигурацию изменения, внесенные администратором сети), написана на Ruby и имеет Ruby-подобный DSL. Это приложение позволяет централизованно управлять конфигурацией ПО, установленного на нескольких компьютерах.
В статье проводится сравнение преимуществ и недостатков этих SCM.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector