Как отменить коммит в svn
Перейти к содержимому

Как отменить коммит в svn

  • автор:

Как отменить коммит в svn

Если вы желаете отменить все изменения, сделанные вами в файле после его последнего обновления, вам надо отметить файл, правым щелчком вызвать контекстное меню, и затем выбрать команду TortoiseSVN → Убрать изменения Появится диалог, показывающий изменённые вами файлы, которые вы можете вернуть в исходное состояние. Отметьте те, которые вы желаете вернуть и нажмите ОК .

Рисунок 4.35. Диалог ‘Убрать изменения’

Диалог

Если вы также хотите очистить все настроенные списки изменений, то установите флажок в нижней части диалога.

Если вы хотите отменить удаление или переименование, то следует использовать «Убрать изменения» на родительской папке, т. к. удаленный элемент не существует и вы не сделаете на нем правый клик.

Если вы желаете отменить добавление элемента, то в контекстном меню для этого есть команда TortoiseSVN → Отменить добавление. . На самом деле это та же команда ‘Убрать изменения’, но имя было изменено, чтобы сделать её предназначение более очевидным.

Столбцы в этом диалоге могут настраиваться таким же образом, как и столбцы в диалоге Проверка на наличие изменений . Прочтите «Локальный и удалённый статус» если вам необходима дополнительная информация.

Поскольку возврат в прежнее состояние иногда используется для очистки рабочей копии, здесь есть дополнительная кнопка, которая позволяет удалить также и неверсированные элементы. При щелчке на этой кнопке появляется ещё одно окно со списком всех неверсированных элементов, которые вы можете выбрать для последующего удаления.

Отмена зафиксированных изменений

Команда Убрать изменения отменяет только ваши локальные изменения. Она не отменяет изменения, которые уже были зафиксированы. Если вы желаете отменить все изменения, которые были зафиксированы в конкретной ревизии, прочтите «Диалоговое окно журнала ревизий» для дополнительной информации.

Отмена изменений работает медленно

При убирании изменений, вы можете обнаружить, что эта операция занимает намного больше времени, чем вы ожидали. Это происходит потому, что изменённая версия файла отправляется в корзину, чтобы вы могли получить ваши изменения обратно, если убрали их по ошибке. Однако, если ваша корзина заполнена, Windows тратит много времени на поиск места для файла. Решение простое: или очистите корзину, или отключите флажок Использовать корзину при убирании изменений в настройках TortoiseSVN.

Пред. Наверх След.
Удаление, перемещение и переименование Начало Очистка

Svn. Откат изменений на сервере

Бывает накомитешь какашек — потом жалеешь. Вот пилюля для отката изменений на сервере:

svn diff -r 73:68 http&#58//my.repository.com/my/project/trunk

73 — наша текущая ревизия
68 — куда хотим откатиться

Смотрим дейстивтельно ли только мы вносили изменения файл. Если нет, то придется откатыватся вручную — через редактирования проблемных участков с последующим комитом. Если все ок:

svn merge —dry-run -r 73:68 http&#58//my.repository.com/my/project/trunk/

Смотрим что будет мержиться, если нет никаких конфликтов идем дальше:

svn merge -r 73:68 http&#58//my.repository.com/my/project/trunk/

svn merge просматривает измениния между 73 и 68 ревизией и применяет их к вашей рабочей копии

svn commit -m «Reverted to revision 68.»

Пушистых Вам багов, господа!

IgorKa — Информационный ресурс

Немного обо всем и все о немногом, или практический опыт системного администратора.

Февраль 2013

Пн Вт Ср Чт Пт Сб Вс
« Янв Март »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28

Отменить последний коммит в SVN

Calendar

3 февраля 2013, 17:15

Иногда, возникает ситуация когда нужно отменить последний коммит в SVN. Причины могут быть разные. Например, бывает, что разработчик работает с несколькими ветками и по ошибке делает svn commit не в ту ветку. В этом случае нужно вернуть код на момент предпоследнего коммита. Если говорить более правильно, то отменить коммит нельзя. Здесь под операцией отмены подразумевается еще одна операция svn commit, которая отменит изменения последнего коммита.

И это можно сделать всего двумя командами: svn merge и собственно svn commit.
Допустим, что последняя ревизия 44 ошибочна и нам нужно вернуть содержимое SVN на сервере до 43 ревизии.

Если коротко, то нужно всего-навсего выполнить вот такую команду merge (команда должна быть выполнена из корневого каталога рабочей копии.):

$ svn merge -c -44 .

-44 — это номер последней ошибочной ревизии со знаком минус.

А затем выполнить svn commit:

$ svn commit -m «Commit 44 was reverted»

Теперь чуть подробнее и с примерами. С операцией svn merge я более менее знаком хорошо, а вот то, что параметр может принимать отрицательные значения я узнал недавно. И в этом минусе и содержится весь “фокус”. Хотя все логично.

Если выполнить команду svn merge с параметром –dry-run, то мы увидим какие файлы будут изменены:

$ svn merge -c 44 . —dry-run

Как видим ничего изменено не будет, так как рабочая копия (файлы на нашем локальном компьютере) и копия на сервере SVN одинаковы.

А вот если выполним команду вот так (с минусом):

$ svn merge -c -44 . —dry-run
— Reverse-merging r44 into ‘.’:
U svn1.txt
U 1.txt

то увидим, что два файла будут изменены и будет выполнен Reverse-merging ревизии 44 в нашу рабочую копию.

Команда svn diff покажет что будет изменено:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Можем видеть, что из обеих фалов будет удалена строка New Text, которая и была добавлена в 44-й ревизии. И наша рабочая копия будет соответствовать ревизии 43. И эту версию рабочей копии мы и отправим на сервер (это будет ревизия 45), которая будет такой же как и ревизия 43.

Итак, пробуем. В рабочей копии сейчас находится последняя ошибочная ревизия — 44. Вот содержимое файлов:

1
2
3
4
5
6
7
8
9
10
11

$ cat ./1.txt
qwey
New Text
$ cat ./svn1.txt
STRIng1, qwerty
String2, asdfg, qazwsxedc
String3
String4
123
123
New Text

Выполняем команду svn merge:

$ svn merge -c -44 .
— Reverse-merging r44 into ‘.’:
U svn1.txt
U 1.txt
— Recording mergeinfo for reverse merge of r44 into ‘.’:
U .
— Eliding mergeinfo from ‘.’:
U .

Проверяем рабочую копию:

$ svn st
M svn1.txt
M 1.txt

Смотрим содержимое файлов:

$ cat ./1.txt
qwey
$ cat ./svn1.txt
STRIng1, qwerty
String2, asdfg, qazwsxedc
String3
String4
123
123

Теперь можно отправлять текущую версию рабочей копии на сервер:

$ svn commit -m «Commit 44 was reverted»
Sending 1.txt
Sending svn1.txt
Transmitting file data ..
Committed revision 45.

Чтобы убедится, что ревизия 45 точно такая же как и 43-я выполним команду:

$ svn diff -r43:45

Разницы нет. А это значит, что мы “отменили” последний неверный коммит (44-й).

Спасибо за то что поделились ссылкой!

TagТеги: SVN
CategoryРубрика: Закладки | CommentsОтзывы (RSS)

Статьи и новости схожей тематики:

How do I revert an SVN commit?

But neither of them seems to work. I tried those commands and checked the files that were changed by hand. How do I revert a commit with revision number 1944? How do I check that the revert has been done (without looking in the actual file to the changes have been reverted)?

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
asked Nov 11, 2012 at 9:42
41.9k 90 90 gold badges 263 263 silver badges 479 479 bronze badges
Did you never accept an answer because none of them worked?
Apr 16, 2014 at 19:40
If you want a literal answer use «svn merge -c -1944 .» To check if it worked: «svn diff»
Nov 14, 2014 at 21:50
Feb 29, 2016 at 7:30
Possible duplicate of How do I return to an older version of our code in Subversion?
Nov 29, 2016 at 15:01

14 Answers 14

Both examples must work, but

svn merge -r UPREV:LOWREV . undo range

svn merge -c -REV . undoes a single revision, in your case REV would be 1944, i.e. the revision you wish to undo.

in this syntax — if current dir is WC and (as in must done after every merge) you’ll commit results

Do you want to see logs?

45 6 6 bronze badges
answered Nov 11, 2012 at 11:12
Lazy Badger Lazy Badger
95k 9 9 gold badges 79 79 silver badges 110 110 bronze badges
@dwjohnston — yes, merges always performed in WC and it’s not server-side task
Mar 6, 2014 at 2:29
svn: Merge source required . No dice.
Apr 16, 2014 at 19:46
@2rs2ts looks like you forgot the trailing dot to designate ‘do this in the current directory’.
Apr 28, 2014 at 17:09
you can also do multiple single commits at the same time: svn merge -c -42587,-42589 .
Nov 7, 2014 at 18:57

For the second one, if it doesn’t work you probably forgot the — (hyphen) before the revision number.

Apr 28, 2017 at 9:50

If you’re using the TortoiseSVN client, it’s easily done via the Show Log dialog.

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Sep 24, 2013 at 5:16
dodgy_coder dodgy_coder
12.4k 11 11 gold badges 54 54 silver badges 67 67 bronze badges
This is outdated. There no longer is a Context-Menu available for the client in the current version.
Dec 29, 2015 at 18:19

What? TortoiseSVN IS a context menu, plus the dialogs it spawns. What do you mean by «there no longer is a context menu»? There most certainly is!

Mar 1, 2016 at 19:01

@Ben I think user1789573 was getting a bit tripped up over the explicit mention of «Context Menu» in the tutorial linked to in the answer.

Aug 24, 2016 at 19:49

In case you’re seeing this later, it is (still) there. In the show log screen, right click the revision and there’s a «Revert to This Revision» option. This is in TortoiseSVN 1.9.4 Build 27285. I just used it and can tell you it works just fine.

Jan 18, 2017 at 23:13

@MarkkuK. The OP doesn’t specify the OS that is used and last time I checked TortoiseSVN is Windows-only.

Feb 16, 2018 at 9:48

svn merge -r 1944:1943 . should revert the changes of r1944 in your working copy. You can then review the changes in your working copy (with diff), but you’d need to commit in order to apply the revert into the repository.

227k 43 43 gold badges 374 374 silver badges 367 367 bronze badges
answered Nov 11, 2012 at 9:53
3,620 1 1 gold badge 18 18 silver badges 22 22 bronze badges

Does not work, requires merge source. Tried svn merge -r 1944:1943 . instead, but nothing has changed.

Nov 11, 2012 at 10:00

Has the repository advanced since r1944? If so, are there conflicting changes on the same lines as the changes between r1943 and r1944?

Nov 11, 2012 at 10:02

I am at revision 1945 and there does not seem to be a conflict. Neither svn status nor svn diff gives anything.

Nov 11, 2012 at 10:12
Error: svn: Try ‘svn help’ for more info svn: Merge source required
Nov 11, 2012 at 10:19

But svn merge -r 1945:1943 . seem to have worked. I think I understand: You need to merge the version from ‘before’ the ‘bad’ commit into your working repository. This is ok when you want to do a simple ‘revert’ of the previous commit. But what if you want to revert the changes made with version 1900?

Nov 11, 2012 at 10:22

First, undo the changes made in revision 1944.

> svn merge -c -1944 . 

Second, check what is about to be commited.

> svn status 

Third, commit version 1945.

> svn commit -m "Fix bad commit." 

Fourth, look at the new log.

> svn log -l 4 ------------------------------------------------------------------------ 1945 | myname | 2015-04-20 19:20:51 -0700 (Mon, 20 Apr 2015) | 1 line Fix bad commit. ------------------------------------------------------------------------ 1944 | myname | 2015-04-20 19:09:58 -0700 (Mon, 20 Apr 2015) | 1 line This is the bad commit that I made. ------------------------------------------------------------------------ 1943 | myname | 2015-04-20 18:36:45 -0700 (Mon, 20 Apr 2015) | 1 line This was a good commit. ------------------------------------------------------------------------ 

19k 13 13 gold badges 54 54 silver badges 47 47 bronze badges
answered Apr 21, 2015 at 2:25
Shaun Luttin Shaun Luttin
135k 83 83 gold badges 412 412 silver badges 471 471 bronze badges

It is impossible to «uncommit» a revision, but you can revert your working copy to version 1943 and commit that as version 1945. The versions 1943 and 1945 will be identical, effectively reverting the changes.

answered Nov 11, 2012 at 10:00
Jakub Zaverka Jakub Zaverka
8,826 3 3 gold badges 32 32 silver badges 48 48 bronze badges

Just to be annoyingly accurate, I would comment that if you have admin access to the repository, you can «uncommit». This by creating a clone repository up to a given revision using svn dump and then svn load . But, of course, this shouldn’t be used in normal circumstances.

Nov 11, 2012 at 10:06

I do not want to uncommit, I want to create a new commit number with a certain commit inversed. Sets say I have checked out version 1944, made a commit in 1945, which I want to ‘revert’. Then I want to have a version 1946, whose files are identical to the ones in version 1944. (Except the history of course.) But the question remains: How to do that? What are the commands?

Nov 11, 2012 at 10:11

// , @Alex, I am interested in this, too, especially in something analogous to $ git revert . I’ve found it somewhat difficult to learn SVN after using Git for so long.

Feb 6, 2017 at 20:30

The following will do a dry run, as it says. HEAD being current version, PREV is previous, then the path to your file, or committed item:

svn merge --dry-run -rHEAD:PREV https://example.com/svn/myproject/trunk 

If the dry run looks good, run the command without the —dry-run

Verify the change in revision and re-commit. To browse for version numbers try:

svn log 

answered Mar 26, 2014 at 3:49
BentheFolker BentheFolker
301 3 3 silver badges 5 5 bronze badges

F=code.c REV=123 svn diff -c $REV $F | patch -R -p0 \ && svn commit -m "undid rev $REV" $F 

answered Oct 1, 2013 at 12:18
400 3 3 silver badges 6 6 bronze badges
Does this require the local copy to be different from the bad revision?
Jul 22, 2019 at 23:59

While the suggestions given already may work for some people, it does not work for my case. When performing the merge, users at rev 1443 who update to rev 1445 , still sync all files changed in 1444 even though they are equal to 1443 from the merge. I needed end users to not see the update at all.

If you want to completely hide the commit it is possible by creating a new branch at correct revision and then swapping the branches. The only thing is you need to remove and re add all locks.

copy -r 1443 file:/// file:/// svn move file:/// file:/// svn move file:/// file:///

This worked for me, perhaps it will be helpful to someone else out there =)

12.5k 11 11 gold badges 44 44 silver badges 61 61 bronze badges
answered Nov 4, 2014 at 22:27
21 1 1 bronze badge

svn merge -c -M PATH 

This saved my life.

I was having the same issue, after reverting back also I was not seeing old code. After running the above command I got a clean old version code.

5,747 72 72 gold badges 58 58 silver badges 129 129 bronze badges
answered Sep 8, 2016 at 13:47
amit ghosh amit ghosh
31 3 3 bronze badges

Alex, try this: svn merge [WorkingFolderPath] -r 1944:1943

6,143 13 13 gold badges 69 69 silver badges 98 98 bronze badges
answered Jun 26, 2013 at 10:26
422 5 5 silver badges 14 14 bronze badges

I tried the above, ( svn merge ) and you’re right, it does jack. However

svn update -r  [-R] 

seems to work, but isn’t permanent (my svn is simply showing an old revision). So I had to

mv  svn update mv  svn commit -m "Reverted commit on "

In my particular case my target is interfaces/AngelInterface.php . I made changes to the file, committed them, updated the build computer ran the phpdoc compiler and found my changes were a waste of time. svn log interfaces/AngelInterface.php shows my change as r22060 and the previous commit on that file was r22059. So I can svn update -r 22059 interfaces/AngelInterface.php and I end up with code as it was in -r22059 again. Then :-

mv interfaces/AngelInterface.php interfaces/AngelInterface.php~ svn update interfaces/AngelInterface.php mv interfaces/AngelInterface.php~ interfaces/AngelInterface.php svn commit -m "reverted -r22060" interfaces/AngelInterface.php 

Alternatively I could do the same thing on a directory, by specifying . -R in place of interfaces/AngelInterface.php in all the above.

answered Sep 5, 2014 at 15:30
1,242 14 14 silver badges 26 26 bronze badges

One other thing, as was already said, what you can’t do is remove the commit from history, like you can do in git by hacking the refs directly. All you can do, is use the repository to change your source to how you intend it, and commit that as a change.

Sep 5, 2014 at 15:30

Having investigated further I can see that it is possible to remove the commit from history using svnadmin but you’re strongly advised against it. See stackoverflow.com/questions/5566327/…

Sep 5, 2014 at 15:48

If you want to completely remove commits from history, you can also do a dump of the repo at a specific revision, then import that dump. Specifically:

svnrdump dump -r 1:  > filename.dump 

The svnrdump command performs the same function as svnadmin dump but works on a remote repo.

Next just import the dump file into your repo of choice. This was tested to worked well on Beanstalk.

27k 16 16 gold badges 82 82 silver badges 98 98 bronze badges
answered Mar 15, 2017 at 22:48
146 1 1 silver badge 6 6 bronze badges

I have found that the svnrdump generates different dump than the svnadmin dump . I think that might lead to unexact repository move (move with changes). The noticed differences, for example, were in hashes. The svnrdump creates md5 , when the svnadmin dump created md5 + sha* or something like that. Another difference was in the dump file size which was greater in twice for the svnadmin dump .

Nov 7, 2021 at 22:24

Very old thread, however there is no answer for Intellij. To revert a single commit:

Go to: Subversion -> Integrate Directory.

integrate directory view

answered Jan 27, 2021 at 11:04
1,223 12 12 silver badges 24 24 bronze badges

Note that the svn merge command reverts a commit in the sense of having another commit undoing your changes, but keeping your wrong commit in the history.

In the case you are a Subversion system administrator (with command line access) and you have to revert a very big mistake (for example, someone committed something that should not be committed for no reason in the world), and if you want to try to completely drop a commit at any cost, even at the risk of destroying the repo:

Step 1. Identify your repository on your server

First of all identify your repository on your server’s filesystem.

Let’s assume that the pathname is /repo . But it may be /home/svn/myrepo or something like that.

The filesystem structure should be something like this:

$ ls -la /repo total 16 drwxr-xr-x. 6 svn svn 86 10 feb 2020 . drwxrwx---. 145 svn svn 4096 22 giu 16.14 .. drwxr-xr-x. 2 svn svn 54 10 feb 2020 conf drwxr-sr-x. 6 svn svn 253 17 giu 11.25 db -r--r--r--. 1 svn svn 2 10 feb 2020 format drwxr-xr-x. 3 svn svn 4096 10 feb 2020 hooks drwxr-xr-x. 2 svn svn 41 10 feb 2020 locks -rw-r--r--. 1 svn svn 229 10 feb 2020 README.txt 

Let’s also assume that your user is called svn like in the above example.

NOTE: if you don’t know what this is talking about, you probably have not your own Subversion server and this answer may be not useful for your case. Please try other answers (where you just need to have the URL of the server, without physical access).

Step 2. Export your good history

Let’s assume that your wrong revision is 100 and your correct version is 99 :

svnadmin dump -r 1:99 /repo > export.dump 

Step 3. Backup and re-init your repository

Create a backup of your repository and initialize it again:

mv /repo /repo.bak mkdir /repo svnadmin create /repo 

Step 4. Import your good history again

svnadmin load /repo < export.dump 

Now, make sure to fix your permissions with the right user:

chown -R svn:svn /repo 

Is everything working? That's all! Good for you!

BUT at this point there are interesting chances you have destroyed your whole repository. For example, you may no longer be able to checkout, or, your Subversion web application (Phabricator?) may scream with weird error messages, or, you could have killed a thousand kittens by mistake in the process.

If something goes wrong stay ready with your disaster recovery:

Disaster recovery

If a disaster happen:

mv /repo /repo.fail mv /repo.bak /repo 

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

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