IT story

버전이없는 버전의 Subversion 자동 제거

hot-time 2020. 8. 4. 22:51
반응형

버전이없는 버전의 Subversion 자동 제거


버전 관리가없는 작업 복사본의 모든 파일을 재귀 적으로 제거하는 방법을 아는 사람이 있습니까? (자동 빌드 VMware에서보다 안정적인 결과를 얻으려면 이것이 필요합니다.)


편집하다:

Subversion 1.9.0은이를 수행하는 옵션을 도입했습니다.

svn cleanup --remove-unversioned

그 전에이 파이썬 스크립트를 사용하여 그렇게합니다.

import os
import re

def removeall(path):
    if not os.path.isdir(path):
        os.remove(path)
        return
    files=os.listdir(path)
    for x in files:
        fullpath=os.path.join(path, x)
        if os.path.isfile(fullpath):
            os.remove(fullpath)
        elif os.path.isdir(fullpath):
            removeall(fullpath)
    os.rmdir(path)

unversionedRex = re.compile('^ ?[\?ID] *[1-9 ]*[a-zA-Z]* +(.*)')
for l in  os.popen('svn status --no-ignore -v').readlines():
    match = unversionedRex.match(l)
    if match: removeall(match.group(1))

일을 꽤 잘하는 것 같습니다.


이것은 bash에서 나를 위해 작동합니다.

 svn status | egrep '^\?' | cut -c8- | xargs rm

세스 리노 가 더 좋습니다 :

svn status | grep ^\? | cut -c9- | xargs -d \\n rm -r 

파일 이름에서 버전이없는 폴더와 공백을 처리합니다.

아래 주석에 따라 이것은 Subversion이 알지 못하는 파일 (status =?)에서만 작동합니다. Subversion 알고있는 것 (무시 된 파일 / 폴더 포함)은 삭제되지 않습니다.

Subversion 1.9 이상을 사용하는 경우 간단히 svn cleanup 명령을 --remove-unversioned 및 --remove-ignored 옵션과 함께 사용할 수 있습니다


자동화 된 빌드가 아닌 동일한 작업을 수행 하면서이 페이지를 가로 질러 뛰어갔습니다.

좀 더 살펴본 후 TortoiseSVN에서 ' 확장 컨텍스트 메뉴 '를 발견했습니다 . Shift 키를 누른 상태에서 작업중인 사본을 마우스 오른쪽 단추로 클릭하십시오. TortoiseSVN 메뉴 아래에 ' 버전없는 항목 삭제 ... '를 포함한 추가 옵션이 있습니다 .

이 특정 질문 (즉, 자동화 된 빌드의 맥락에서)에는 적용 할 수 없지만 동일한 작업을 수행하는 다른 사람들에게 도움이 될 것이라고 생각했습니다.


참조 : svn-clean


Windows 명령 행에있는 경우

for /f "tokens=2*" %i in ('svn status ^| find "?"') do del %i

개선 된 버전 :

for /f "usebackq tokens=2*" %i in (`svn status ^| findstr /r "^\?"`) do svn delete --force "%i %j"

이것을 배치 파일에서 사용하면 다음을 두 배로해야합니다 %.

for /f "usebackq tokens=2*" %%i in (`svn status ^| findstr /r "^\?"`) do svn delete --force "%%i %%j"

이것을 Windows Powershell 프로파일에 추가했습니다.

function svnclean {
    svn status | foreach { if($_.StartsWith("?")) { Remove-Item $_.substring(8) -Verbose } }
}

리눅스 커맨드 라인 :

svn status --no-ignore | egrep '^[?I]' | cut -c9- | xargs -d \\n rm -r

또는 일부 파일이 루트 소유인 경우 :

svn status --no-ignore | egrep '^[?I]' | cut -c9- | sudo xargs -d \\n rm -r

이것은 Ken의 답변을 기반으로합니다. (Ken의 대답은 무시 된 파일을 건너 뛰고 내 대답은 파일을 삭제합니다).


새로운 위치로 내보내기 만하고 거기서 만들 수 있습니까?


유닉스 쉘에서 다음을 수행하십시오.

rm -rf `svn st . | grep "^?" | cut -f2-9 -d' '`

당신이 만약 TortoiseSVN을을 경로와 당신이 바로 그 디렉토리에 있습니다 :

TortoiseProc.exe /command:cleanup /path:"%CD%" /delunversioned /delignored /nodlg /noui

옵션은 다음에 대한 TortoiseSVN 도움말에 설명되어 있습니다 /command:cleanup.

/ noui를 사용하면 정리가 완료되었음을 알리거나 오류 메시지를 표시하는 결과 대화 상자가 나타나지 않도록합니다. / noprogressui는 진행률 대화 상자도 비활성화합니다. / nodlg는 정리에서 수행 할 작업을 사용자가 선택할 수있는 정리 대화 상자를 표시하지 않습니다. 사용 가능한 조치는 상태 정리, / revert, / delunversioned, / delignored, / refreshshell 및 / externals에 대해 / cleanup 옵션을 사용하여 지정할 수 있습니다.


Thomas Watnedals Python 스크립트의 C # 변환 :

Console.WriteLine("SVN cleaning directory {0}", directory);

Directory.SetCurrentDirectory(directory);

var psi = new ProcessStartInfo("svn.exe", "status --non-interactive");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.WorkingDirectory = directory;

using (var process = Process.Start(psi))
{
    string line = process.StandardOutput.ReadLine();
    while (line != null)
    {
        if (line.Length > 7)
        {
            if (line[0] == '?')
            {
                string relativePath = line.Substring(7);
                Console.WriteLine(relativePath);

                string path = Path.Combine(directory, relativePath);
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, true);
                }
                else if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }
        line = process.StandardOutput.ReadLine();
    }
}

svn st --no-ignore  | grep '^[?I]' | sed 's/^[?I]  *//' | xargs -r -d '\n' rm -r

이것은 서브 버전 제어하에 있지 않은 모든 파일을 삭제하는 유닉스 쉘 명령입니다.

노트:

  • st에서이 svn st빌드에 대한 별칭 status, 즉 명령에 해당svn status
  • --no-ignore상태 출력에 저장소가 아닌 파일도 포함됩니다. 그렇지 않으면 .cvsignore등의 메커니즘을 통해 무시됩니다 . 목표는 빌드를위한 깨끗한 시작점이 있어야하기 때문에이 스위치는 필수입니다
  • grep전복에 그와 같은 출력은 알 수없는 파일 필터는 남아 있습니다 - 라인은로 시작 ?를 빼고 무시 될 것이다 전복에 대한 목록 파일의 알 수없는 --no-ignore옵션
  • 파일 이름까지의 접두사는 sed
  • xargs명령을 통해 지시를 -r실행하지에 rm인수 목록이 비어 될 때,
  • -d '\n'옵션은 xargs줄 바꿈 문자를 구분 기호로 사용하도록 명령합니다.이 명령은 공백이있는 파일 이름에서도 작동합니다.
  • rm -r 저장소의 일부가 아닌 완전한 디렉토리를 제거해야하는 경우에 사용됩니다.

거북이 svn을 사용하는 경우 숨겨진 명령이 있습니다. 폴더를 마우스 오른쪽 버튼으로 클릭 한 상태에서 Shift 키를 누른 상태에서 Windows 탐색기에서 상황에 맞는 메뉴를 시작하십시오. "버전없는 항목 삭제"명령이 나타납니다.

자세한 내용은이 페이지 하단을 참조하거나 아래의 스크린 샷에서 녹색 별표로 확장 된 기능을 강조 표시하고 아래 그림은 노란색 사각형으로 표시합니다.

SVN 확장 상황에 맞는 메뉴 대 표준 메뉴


버전이없는 항목을 제거하는 Subversion 1.9.0 옵션이 도입되었습니다 [1]

svn cleanup --remove-unversioned

[1] https://subversion.apache.org/docs/release-notes/1.9.html#svn-cleanup-options


추가 종속성없이 위의 작업을 수행 할 수 없었으므로 win32에서 자동 빌드 시스템에 추가하고 싶지 않았습니다. 따라서 다음 Ant 명령을 구성했습니다. Ant-contrib JAR이 설치되어 있어야합니다 (Anant 1.7.0과 함께 최신 버전 1.0b3을 사용하고 있음).

경고없이 버전없는 파일을 모두 삭제합니다.

  <taskdef resource="net/sf/antcontrib/antcontrib.properties"/>
  <taskdef name="for" classname="net.sf.antcontrib.logic.ForTask" />

  <macrodef name="svnExecToProperty">
    <attribute name="params" />
    <attribute name="outputProperty" />
    <sequential>
      <echo message="Executing Subversion command:" />
      <echo message="  svn @{params}" />
      <exec executable="cmd.exe" failonerror="true"
            outputproperty="@{outputProperty}">
        <arg line="/c svn @{params}" />
      </exec>
    </sequential>
  </macrodef>

  <!-- Deletes all unversioned files without warning from the 
       basedir and all subfolders -->
  <target name="!deleteAllUnversionedFiles">
    <svnExecToProperty params="status &quot;${basedir}&quot;" 
                       outputProperty="status" />
    <echo message="Deleting any unversioned files:" />
    <for list="${status}" param="p" delimiter="&#x0a;" trim="true">
      <sequential>
        <if>
          <matches pattern="\?\s+.*" string="@{p}" />
          <then>
            <propertyregex property="f" override="true" input="@{p}" 
                           regexp="\?\s+(.*)" select="\1" />
            <delete file="${f}" failonerror="true" />
          </then>
        </if>
      </sequential>
    </for>
    <echo message="Done." />
  </target>

다른 폴더의 경우 ${basedir}참조를 변경하십시오 .


svn status --no-ignore | awk '/^[I\?]/ {system("echo rm -r " $2)}'

원하는 작업이 확실하면 에코를 제거하십시오.


다른 사람들이하고 있기 때문에 ...

svn status | grep ^? | awk '{print $2}' | sed 's/^/.\//g' | xargs rm -R

다른 옵션을 제공 할 수도 있습니다

svn status | awk '{if($2 !~ /(config|\.ini)/ && !system("test -e \"" $2 "\"")) {print $2; system("rm -Rf \"" $2 "\"");}}'

/(config|.ini)/는 저의 목적입니다.

svn 명령에 --no-ignore를 추가하는 것이 좋습니다.


RH5 시스템에서 svn-clean을 우연히 발견했습니다. / usr / bin / svn-clean에 있습니다.

http://svn.apache.org/repos/asf/subversion/trunk/contrib/client-side/svn-clean


순수한 Windows cmd / bat 솔루션 :

@echo off

svn cleanup .
svn revert -R .
For /f "tokens=1,2" %%A in ('svn status --no-ignore') Do (
     If [%%A]==[?] ( Call :UniDelete %%B
     ) Else If [%%A]==[I] Call :UniDelete %%B
   )
svn update .
goto :eof

:UniDelete delete file/dir
if "%1"=="%~nx0" goto :eof
IF EXIST "%1\*" ( 
    RD /S /Q "%1"
) Else (
    If EXIST "%1" DEL /S /F /Q "%1"
)
goto :eof

이 답변 에서 Seth Reno의 버전을 사용해 보았지만 효과가 없었습니다. 에 사용 된 9가 아닌 파일 이름 앞에 8 문자가 있습니다.cut -c9-

그래서 이것은 sed대신에 내 버전 입니다 cut.

svn status | grep ^\? | sed -e 's/\?\s*//g' | xargs -d \\n rm -r

powershell로 시원하다면 :

svn status --no-ignore | ?{$_.SubString(0,1).Equals("?")} | foreach { remove-item -Path (join-Path .\ $_.Replace("?","").Trim()) -WhatIf }

명령이 실제로 삭제를 수행하게하려면 -WhatIf 플래그를 사용하십시오. 그렇지 않으면 -WhatIf없이 실행하면 수행 작업 만 출력됩니다 .


나는 이것을 Thomas Watnedal의 답변에 대한 의견으로 추가 하지만 아직 할 수는 없습니다.

Windows에 영향을 미치지 않는 사소한 문제는 파일이나 디렉토리 만 검사한다는 것입니다. 심볼릭 링크가 존재할 수있는 유닉스 계열 시스템의 경우 라인을 변경해야합니다.

if os.path.isfile(fullpath):

if os.path.isfile(fullpath) or os.path.islink(fullpath):

또한 링크를 제거합니다.

For me, changing the last line if match: removeall(match.group(1)) into

    if match:
        print "Removing " + match.group(1)
        removeall(match.group(1))

so that it displays what it is removing was useful too.

Depending on the use case, the ?[\?ID] part of the regular expression may be better as ?[\?I], as the D also removes deleted files, which were under version control. I want to use this to build in a clean, checked in folder, so there should be no files in a D state.


@zhoufei I tested your answer and here is updated version:

FOR /F "tokens=1* delims= " %%G IN ('svn st %~1 ^| findstr "^?"') DO del /s /f /q "%%H"
FOR /F "tokens=1* delims= " %%G IN ('svn st %~1 ^| findstr "^?"') DO rd /s /q "%%H"
  • You must use two % marks in front of G and H
  • Switch the order: first remove all files, then remove all directories
  • (optional:) In place of %~1 can be used any directory name, I used this as a function in a bat file, so %~1 is first input paramter

If you don't want to write any code, svn2.exe from svn2svn does this, also there's an article on how it's implemented. Deleted folders and files are put in the recycle bin.

Run "svn2.exe sync [path]".


For the people that like to do this with perl instead of python, Unix shell, java, etc. Hereby a small perl script that does the jib as well.

Note: This also removes all unversioned directories

#!perl

use strict;

sub main()

{

    my @unversioned_list = `svn status`;

    foreach my $line (@unversioned_list)

    {

        chomp($line);

        #print "STAT: $line\n";

        if ($line =~/^\?\s*(.*)$/)

        {

            #print "Must remove $1\n";

            unlink($1);

            rmdir($1);

        }

    }

}

main();

Using TortoiseSVN: * right-click on working copy folder, while holding the shift-key down * choose "delete unversioned items"

How can I delete all unversioned/ignored files/folders in my working copy?


A clean way to do this in PERL would be:

#!/usr/bin/perl
use IO::CaptureOutput 'capture_exec'

my $command = sprintf ("svn status --no-ignore | grep '^?' | sed -n 's/^\?//p'");

my ( $stdout, $stderr, $success, $exit_code ) = capture_exec ( $command );
my @listOfFiles = split ( ' ', $stdout );

foreach my $file ( @listOfFiles )
{ # foreach ()
    $command = sprintf ("rm -rf %s", $file);
    ( $stdout, $stderr, $success, $exit_code ) = capture_exec ( $command );
} # foreach ()

나는 이것을 생성하기 위해 ~ 3 시간을 사용했습니다. 유닉스에서는 5 분이 걸립니다. 주요 문제는 Win 폴더 이름의 공백, %% i 편집 불가능 및 Win cmd 루프에서 vars 정의 관련 문제였습니다.

setlocal enabledelayedexpansion

for /f "skip=1 tokens=2* delims==" %%i in ('svn status --no-ignore --xml ^| findstr /r "path"') do (
@set j=%%i
@rd /s /q !j:~0,-1!
)

위의 C # 코드 스 니펫이 나를 위해 작동하지 않았습니다-나는 svn 클라이언트를 가지고 있으며 라인의 형식이 약간 다릅니다. 위와 동일한 코드 스 니펫은 정규식을 사용하고 기능으로 다시 작성되었습니다.

        /// <summary>
    /// Cleans up svn folder by removing non committed files and folders.
    /// </summary>
    void CleanSvnFolder( string folder )
    {
        Directory.SetCurrentDirectory(folder);

        var psi = new ProcessStartInfo("svn.exe", "status --non-interactive");
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.WorkingDirectory = folder;
        psi.CreateNoWindow = true;

        using (var process = Process.Start(psi))
        {
            string line = process.StandardOutput.ReadLine();
            while (line != null)
            {
                var m = Regex.Match(line, "\\? +(.*)");

                if( m.Groups.Count >= 2 )
                {
                    string relativePath = m.Groups[1].ToString();

                    string path = Path.Combine(folder, relativePath);
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }
                    else if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
                line = process.StandardOutput.ReadLine();
            }
        }
    } //CleanSvnFolder

참고 URL : https://stackoverflow.com/questions/239340/automatically-remove-subversion-unversioned-files

반응형