pax_global_header00006660000000000000000000000064117751052600014516gustar00rootroot0000000000000052 comment=38aa77b369851d1cd457f63213883eea3aefb74d svnkit-1.7.5+dfsg/000077500000000000000000000000001177510526000137655ustar00rootroot00000000000000svnkit-1.7.5+dfsg/CHANGES.txt000066400000000000000000000465561177510526000156160ustar00rootroot00000000000000== version 1.7.5 == + File externals merge issues fixed. + SVNStatus reported for old and new working copy formats made more consistent. + Existing credentials in default cache are no longer overwritten by truncated ones when store-passwords option is set to false. + Deleting a file remotely resulted in grand-parent directory access, fixed. + SVNLogClient.doList(recursive=false) now uses SVNDepth.IMMEDIATES, not FILES. + SqlJet 1.1.3 is used and potential NPE on concurrent working copy access fixed. + Other minor stability improvements and bugfixes. == version 1.7.4-v1 == + SVNLogClient.doList() method issues fixed. + Potential PRISTINE wc.db table corruption fixed. + SVNWCClient.doResolve() was choosing wrong file version when resolving conflict, fixed. + JavaHL SVNClient reported wrong version, fixed. + Minor stability improvements and bugfixes. + Build script upgraded to use Gradle 1.0-rc3. == version 1.7.4 == + Minor diff generator improvements + ISvnOperationHandler callback added to let users receive notifications before and after operation. == version 1.7.4-rc5 == + All snapshot dependencies are replaced with fixed versions. + NPE on remote proplist opertation fixed. + Incompatibility with GitHub Subversion bridge fixed (commit did not work) == version 1.7.4-rc4 == + Fixed issue with Eclipse update site. + Fixed critical issue with switch leaving invalid wc props, thus resulting in potentially wrong commits destination. == version 1.7.4-rc3 == + Few backward compatibility issues fixed. + SqlJet Library dependency upgraded to 1.1.0 + Added: SVNStatus.getCombinedNodeAndContentsStatus() method + Added: More javadoc documentation == version 1.7.4-rc2 == * Fixed: JavaHL ConflictDescriptor object contained relative paths in place of absolute, fixed * Fixed: base checksum were not passed to the ISVNEditor callback on file update over DAV. * Fixed: Repository to repository copy did not work with old working copy in certain cases. + Added: More javadoc documentation == version 1.7.4-rc1 == + Performance and stability improvements * Version bumped to match that of compatible native Subversion == version 1.7.0-beta3 == + Performance and stability improvements + Diff operation improvements * This is a beta version and it may not be stable enough for production environment == version 1.7.0-beta2 == + Performance and stability improvements * This is a beta version and it may not be stable enough for production environment == version 1.7.0-beta1 == * First beta version with new Subversion 1.7 working copy format support + Lot of fixes and improvements in the new working copy format support, since alpha2 * This is a beta version and it may not be stable enough for production environment == version 1.7.0-alpha2 == + New JavaHL API (org.apache.subversion.javahl) implementation + Lot of fixes and improvements in the new working copy format support * This is alpha version and it may not be stable enough for production environment * The following operations are not yet implemented for the new working copy format: - merge - diff == version 1.7.0-alpha1 == + New Subversion 1.7 working copy format support + New high-level API (see org.tmatesoft.svnkit.core.wc2) * This is alpha version and it may not be stable enough for production environment * The following operations are not yet implemented for the new working copy format: - merge - mergeinfo - diff - resolve, mark resolved - cleanup * new JavaHL API is not yet implemented in this version == version 1.3.7 == + 1.7 Subversion servers compatibility issues fixed. + Export operation failed on missing directories, fixed. * For new 1.7 Subversion working copy format support please use SVNKit 1.7.0-alpha version. == version 1.3.6.1 == + OSGi bundle exports JavaHL API package. == version 1.3.6 == + Changes made in Subversion since version 1.6.15 implemented, all Subversion 1.6.17 features are supported. + SSH connections pool reimplemented, number of race conditions and potential deadlocks fixed by that new implementation. + Memory consumption decreased significantly for status operation. + GNOME keyring support + HTTP Digest and Basic authentication methods did not work with non Keep-Alive connection, fixed. + SQLJet library upgraded to v1.0.7 + Other minor bugfixes and improvements. == version 1.3.5 == + Changes made in Subversion since version 1.6.12 implemented, all Subversion 1.6.15 features are supported. + Support for OS X Keychain as credentials storage added. + SSL client certificate passphrase is cached in a way compatible with that of the native Subversion. + HTTP cookies are handled properly. + SQLJet library upgraded to v1.0.4 + Other minor bugfixes and improvements. == version 1.3.4 == + Changes made in Subversion since version 1.6.11 implemented, all Subversion 1.6.12 features are supported. + Added support for SSH host fingerprints verification. + Name conflict status added which is reported on case-insensitive filesystems for files which name differs only in case. + HTTP digest authentication support improved. + svnkit:charset property support significantly improved. + SQLJet library upgraded to v1.0.3 + JNA library upgraded to v3.2.7 + Other minor bugfixes and improvements. == version 1.3.3 == + Changes made in Subversion since version 1.6.6 implemented, all Subversion 1.6.11 features are supported. + HTTP Negotiate authentication improvements. + Support of MSCAPI SSL certificates added. + SQLJet library upgraded to version 1.0.2 + File externals support improved + Other bugfixes == version 1.3.2 == + Changes made in Subversion since version 1.6.5 implemented, all Subversion 1.6.6 features are supported. * Negotiate authorization mechanism was not used when multiple authorization schemes were offered to client by server. * SQLJet library upgraded to version 1.0.1. * JNA library upgraded to version 3.2.3. + Bugfixes and performance improvements. == version 1.3.1 == + Changes made in Subversion since version 1.6.2 implemented, all Subversion 1.6.5 features are supported. * Representation cache DB support, using SQLJet (http://sqljet.com) library. * Added implementations for couple of missing JavaHL methods. * Fixed 'svn: Checksum mismatch while reading representation' exception on reading vdelta from local repositories. * Several dump and load operation issues fixed. * JNA library upgraded to version 3.1.0. + Other bugfixes and performance improvements. == version 1.3.0 + Changes made in Subversion since version 1.5.6 implemented, all Subversion 1.6.2 features are supported: * Tree conflicts handled more gracefully * File-externals support for intra-repository files * File protocol: 1.6.2 Subversion repositories format supported * Administrative tools: support for packing repository shards * Command line client: repository root relative URL support on most commands * Performance improvements on huge files during update\commits + Other bugfixes and performance improvements. == version 1.3.0-beta3 + Changes made in Subversion since version 1.5.6 implemented, all Subversion 1.6.1 features are supported. + Bugfixes since version 1.3.0-beta2 == version 1.3.0-beta2 + Changes made in Subversion since version 1.5.6 implemented, all Subversion 1.6.1 features are supported. + JavaHL implementation bugfixes. + Compatibility with pre-1.6 working copies improved for 'no working copy upgrade' cases. + Update performance on large files improved. + Command line client improvements. + Other bugfixes and performance improvements. == version 1.3.0-beta + Changes made in Subversion since version 1.5.6 implemented, all Subversion 1.6.1 features are supported. + Merge tracking bugfixes + Other bugfixes and performance improvements. == version 1.2.3 + Changes made in Subversion since version 1.5.5 implemented, all Subversion 1.5.6 features are supported. + Merge tracking bugfixes + Better interacting with external diff programs + svnkit.no.safe.copy system property introduced for file system copy operations + Other bugfixes and performance improvements. == version 1.2.2 + Changes made in Subversion since version 1.5.4 implemented, all Subversion 1.5.5 features are supported. + Merge tracking implementation changed to match Subversion 1.5.5. + HP-UX support added. + Other stability and performance improvements. == version 1.2.1 + Changes made in Subversion since version 1.5.0 implemented, all Subversion 1.5.4 features are supported. + JNA library updated to version 3.0.9. + JNA-based code fixed to work properly on amd64 systems. + HTTP Negotiate authentication scheme support added. + "Fast" update feature has been added to SVNUpdateClient API. + Command line client improvements. + Other stability and performance improvements. == version 1.2.0 + Possible NPE on WC to URL copy operation fixed. + Log operation didn't work properly with 'limit' options set to value larger than Integer.MAX_VALUE, fixed. + OSGI manifest fixes. == version 1.2.0-rc4 + JNA library updated to version 3.0.5. + jsvnlook 'cat' and 'lock' commands added. + Update operation didn't work properly on sparse directories with 1.4.x Subversion servers, fixed. + SASL: minor bugfixes. + Other bugfixes. == version 1.2.0-rc3 + SVNKit Eclipse plugin divided into two features: core svnkit library and optional JNA library. + SVNKit Eclipse plugin made compatible with base OSGI framework. + SVN+SSH protocol performance improvements. + File uid and guid wasn't properly fetched on OSX and BSD. + Other bugfixes and minor improvements. == version 1.2.0-rc2 + SASL: incorrect output buffer size might result in failed commits, fixed. + Possible NPE on copy operation fixed. == version 1.2.0-rc1 + Javadoc updated + SASL authentication support bugfixes + Bug in keyword expansion code fixed + Other bugfixes == version 1.2.0-beta5 + SASL authentication support improved + Java SSH Trilead library updated to build 213 + JNA library updated to version 3.0.4 + Fixed: SSH connectivity problems with non-OpenSSH servers + Javadoc updated + Other bugfixes == version 1.2.0-beta4 + Bugfixes == version 1.2.0-beta3 + SASL authentication support improved. + Other bugfixes. == version 1.2.0-beta2 + JavaHL compatiblity bugfixes + DAV protocol performance improvements == version 1.2.0-beta + Subversion 1.5.0 features support == version 1.1.7 + SVNKit didn't work properly with Subversion 1.5.0 servers over svn protocol + JNA library updated to version 3.0.2 + Trilead-SSH library updated to build 212 + Other bugfixes == version 1.1.6 + Bugfixes: + Copy WC to URL sometimes didn't work properly with switched directories. + Several NPEs in HTTP connection code fixed. + Authentication cancellation didn't work with SSH connection in some cases. == version 1.1.5 + Connections pool has been improved. + New version of SSH library (Trilead build 211) is used. + When possible, JNA library is used for most of native calls instead of Runtime.exec(...) + HTTP Digest authentications works better. + Bug in keywords expansion code fixed. + Other bugfixes. = version 1.1.4 + Connections pool closes inactive connections on timeout. + Bugfixes. = version 1.1.3 + Encrypted credentials supported on Windows. + OpenVMS support improved. + Bugfixes. + Daily builds now available at http://teamcity.svnkit.com/ = version 1.1.2 + SVNKit command line client: interactive credentials prompt added. + SVNKit command line client: jsvnversion added. + JavaHL: SVNAdmin implemented using SVNKit API. + System-wide configuration files support (e.g. /etc/subversion on Linux) + bugfixes. = version 1.1.1 + added support for svnlook features. + added support for svnadmin dump/verify/load/rmtxns/lstxns features. + svn, svnadmin, svnlook and svnsync scripts are renamed to jsvn, jsvnadmin, jsvnlook and jsvnsync to distinguish them from the native programs. + command line scripts supports OpenVMS. + bugfixes. = version 1.1.0 + command line application and API to perform svnsync. + bugfixes. = version 1.1.0.beta5 + support for Subversion 1.4 working copy and new fsfs repository format. + support for new features introduced by Subversion 1.4. + bugfixes. = version 1.1.0.beta4 + bug introduced in beta3 version fixed: Eclipse keyring credentials storage support was broken. = version 1.1.0.beta3 + Minor API improvements. + Minor bugfixes. = version 1.1.0.beta2 + NTLM authentication method support. + Javadoc updated to match new SVNKit features. + Minor bugfixes. = version 1.1.0.beta + 'file' protocol support (for 'fsfs' repositories). = version 1.0.3 + improved cancellation support + improved versioned symlinks handling + improved HTTP proxies support + bugfixes = version 1.0.2 + full support of the new Subversion 1.3.0 features. + ssh 'keyboard-interactive' authentication support. + ssl client certificate prompt support. + error codes and error messages hierarchy support in the API. + utility classes to genereta operatios output in XML format. + faster delta generation and delta processing code. + utility API classes to process and generate deltas. + documentations improved, Commit and Export examples simplified. + bugfixes ! Note: This version includes minor API changes and is not binary compatible with the previous versions. API changes are: * String error messages replaced with SVNErrorMessage objects * ISVNFileRevisionHanlder callback interface changed * all callback interfaces methods now declared as throwing SVNException = version 1.0.1 + bugfixes = version 1.0.0 + documentation related improvements + bugfixes = version 0.9.3 + licensing conditions changed + support for atomic commit from different working copies + persistent connections support + improvements in performance and memory consumption + bugfixes = version 0.9.2 + RC2: bugfixes related to configuration handling and svn+ssh authentication = version 0.9.1 + RC1: All features planned for 1.0 version are completed. = version 0.8.8.1 + critical bug in SVNKit Eclipse plugin fixed. = version 0.8.8 + http digest auth support (requires apache version > 2.0.48) + wc->url and url->wc copy operations + use-commit-times option support + bugfixes = version 0.8.7.2 + Subclipse v0.9.30 compatible = version 0.8.7.1 + Subclipse v0.9.29 compatible = version 0.8.7 + http proxy support + svn "keywords" are expanded properly + different eol's in a file are handled correctly + other minor bugfixes = version 0.8.6 + annotate (blame) operation is implemented. + http: server socket close detected properly and doesn't result in operation failure. + SVNClient: absolute paths are used in notifications. + SVNClient: fileContent method traces file renames. + SVNClient: list and logMessages methods return paths sorted alphabetically. + SVNClient: auth info is stored in Eclipse key ring when used within Eclipse. = version 0.8.5 + SVNClient: WC copy and move operations work properly on Linux and OS X. + SVNClient: "conflicted" status is reported correctly during update ("merged" was reported instead). = version 0.8.4 + Subclipse Extension supports Subclipse 0.9.28 + tabulations in externals definitions processed correctly. = version 0.8.3 + children of copied or moved directories were not committed properly when their wc revision was different from the parent's one. + http: all DAV requests (including commit comments) are sent in UTF-8 encoding. + SvnClient: add and remove methods didn't work for directories, fixed. + SvnClient: commit of single file deletion didn't work, fixed. + Eclipse: SVNKit features installed from update site supports automatic update = version 0.8.2 + svn+ssh: persistent ssh connection is used to improve svn+ssh performance. + http: problems with accessing repository location that needs different credentials then repository root is fixed. + http: all paths in requests are canonicalized, some svn server versions failed to process non-canonicalized paths. + wc: changes in externals were not committed correctly over http when using ISVNWorkspace.commit(...), fixed. + SvnClient: diff method implemented (so that Eclipse "generate patch" action works). + SvnClient: copy and move methods fixed to work properly in Subclipse repository view. + SvnClient: setPrompt support, better notifications, "windows" paths are handled correctly. + logging: Pluggable loggers support and detailed http logging added (thanks to Marc Strapez). + logging: Eclipse SVNKit version uses Eclipse logging facilities. = version 0.8.1 + bugs with committing files within moved directories fixed + bugfixes related to operations over http connection + for subclipse users: more detailed console notifications on svn operations = version 0.8.0 + new builds versioning schema introduced + update site with eclipse plugin and subclipse extension added = build 20050131 + import works properly with single file and when importing to non-yet-existing directories + switch works properly when switching single file + more minor bugfixes = build 20050120 + bugs with commiting locally copied files fixed + DAV '/' repository location handled correctly = build 20050112 + lot of incompatibilities with native svn fixed + SVNClient supports remote deletion, copy and move operations = build 20050106 + number of bugs in remote status implementation fixed + ISVNWorkspace.getFileContent method restored to keep binary compatibility + Diff generators framework added, now SVNKit provides API for generating diff in different formats ('unified' and 'normal') for arbitrary input sources = build 20050105 + svn+ssh authentication failed to work in some cases - fixed + revisions in working copy now updated correctly after update + got rid of number of minor inconsistences between SVNKit and native SVN + http and https protocols supports compressed data (gzip) = build 20041223 + ISVNWorkspace.delete now accepts 'force' parameter + bug fixed that prevented Subclipse committing single file in non-windows systems + complete svn and svn+ssh protocol logging may be enabled with -Dsvnkit.log.svn=true command line switch = build 20041221 + when using svn+ssh SVNKit takes private key path from the java property, if it is not defined explicitly + svn+ssh bugfixes + bugfixes = build 20041219 + infinite loop on commits that includes workspace root fixed + JavaHL: SVNClient accepts all revision kinds (DATE, HEAD, etc.) = build 20041217 + bugfixes = build 20041216 + bugfixes = build 20041211 + command line svn client (status, import, checkout are implemented) + python tests launcher to reuse original svn python tests suite + bugfixes = build 20041209 + bugfixes = build 20041204 + bugfixes + SVNKit works with Subclipse 0.9.24 = build 20041130 + bugfixes = build 20041126 + svn+shh protocol support (with the jsch library) + bugfixes = build 20041124 + javahl copy, move and mkdir methods implementation + methods to manage global ignore added to ISVNWorkspace + bugfixes = build 20041123 + recursive property set operation + ISVNWorkspace accepts credentials provider + SSLContext made pluggable + javahl replacement works with Subclipse + bugfixes = build 20041118 + javahl implementation (SvnClient) is included into the library + workspace accepts credentials provider = build 20041116 + bugfixes = build 20041110 + svn:externals support + bugfixes = build 20041109 + bug that prevents checkout sometimes fixed = build 20041108 + authentication API simplified + performance improvements + bugfixes = build 20041105 + switch and relocate operations + bugfixessvnkit-1.7.5+dfsg/LICENSE.txt000066400000000000000000000051271177510526000156150ustar00rootroot00000000000000The TMate License This license applies to all portions of TMate SVNKit library, which are not externally-maintained libraries (e.g. Trilead SSH library). All the source code and compiled classes in package org.tigris.subversion.javahl except SvnClient class are covered by the license in JAVAHL-LICENSE file Copyright (c) 2004-2012 TMate Software. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Redistributions in any form must be accompanied by information on how to obtain complete source code for the software that uses SVNKit and any accompanying software that uses the software that uses SVNKit. The source code must either be included in the distribution or be available for no more than the cost of distribution plus a nominal fee, and must be freely redistributable under reasonable conditions. For an executable file, complete source code means the source code for all modules it contains. It does not include source code for modules or files that typically accompany the major components of the operating system on which the executable file runs. * Redistribution in any form without redistributing source code for software that uses SVNKit is possible only when such redistribution is explictly permitted by TMate Software. Please, contact TMate Software at support@svnkit.com to get such permission. THIS SOFTWARE IS PROVIDED BY TMATE SOFTWARE ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL TMATE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. svnkit-1.7.5+dfsg/README.txt000066400000000000000000000036241177510526000154700ustar00rootroot00000000000000This is a README.txt file for SVNKit - pure Java Subversion client library. 1. DESCRIPTION SVNKit is a pure Java Subversion client library. 2. LICENSING SVNKit is open source product. The complete source code, documentation, and files required to build the library are available for download from our Web site at http://svnkit.com/ The TMate open source license permits you to use SVNKit at no charge under the condition that if you use the software in an application you redistribute, the complete source code for your application must be available and freely redistributable under reasonable conditions. If you do not want to release the source code for your application, you may purchase a license from TMate Software. For pricing information, or if you have further questions on licensing, please contact us at support@svnkit.com. You may find the TMate open source license in COPYING file that is located within the same directory as this file or at http://svnkit.com/license.html 3. FEATURES SVNKit allows to work with Subversion repositories and Subversion working copies. SVNKit features direct repository access as well as support for all high level Subversion operation that are available with the command line Subversion client. This version of SVNKit supports all major Subversion 1.7.5 features. This version of SVNKit supports both new (1.7, sqlite db) and old (1.6 and older) working copy formats as well as all versions of Subversion repositories since 1.0. 4. RESOURCES SVNKit Web Site: http://svnkit.com/ SVNKit Documentation: http://svnkit.com/documentation.html SVNKit Wiki: https://wiki.svnkit.com/ SVNKit JavaDoc: http://svnkit.com/javadoc/ SVNKit Mailing List: http://svnkit.com/support.html SVNKit Issues Tracker: http://svnkit.com/tracker/ SVNKit Continuous Build Server: https://teamcity.svnkit.com/ 5. CONTACTS On all questions related to SVNKit please contact us at support@svnkit.comsvnkit-1.7.5+dfsg/build.defaults.gradle000066400000000000000000000014001177510526000200450ustar00rootroot00000000000000project.ext.setProperty('buildPluginRepositoryURL', 'http://maven.tmatesoft.com/content/repositories/releases/') if (!project.hasProperty('mavenProxyRepository.url')) { setPropertyDefaultValue('mavenTMateSoftSnapshotsRepository.url', 'http://maven.tmatesoft.com/content/repositories/snapshots/') setPropertyDefaultValue('mavenTMateSoftReleasesRepository.url', 'http://maven.tmatesoft.com/content/repositories/releases/') setPropertyDefaultValue('mavenCentralRepository.url', 'http://repo1.maven.org/maven2/') setPropertyDefaultValue('mavenJavaNetRepository.url', 'http://download.java.net/maven/2/') } def setPropertyDefaultValue(String name, String value) { if (!project.hasProperty(name)) { project.ext.setProperty(name, value) } }svnkit-1.7.5+dfsg/build.gradle000066400000000000000000000103571177510526000162520ustar00rootroot00000000000000group = 'org.tmatesoft.svnkit' version = '1.7.5' project.ext { release = true target = '1.5' compatibleSvnVersion = '1.7.5' } apply from: 'build.pom.gradle' buildscript { apply from: 'build.defaults.gradle' configurations.all { resolutionStrategy { cacheChangingModulesFor 0, 'seconds' cacheDynamicVersionsFor 0, 'seconds' } } repositories { maven { url project.ext.buildPluginRepositoryURL } } dependencies { classpath 'org.tmatesoft.build:build:0.9.9' } } task wrapper(type: Wrapper) {} def javaProjects() { return subprojects - project(':svnkit-distribution') } allprojects { apply plugin : 'base' apply plugin : 'build' } configure(javaProjects() + rootProject) { apply plugin: 'eclipse' apply plugin: 'idea' gradle.taskGraph.whenReady { taskGraph -> taskGraph.allTasks.each { task -> if (task.name == 'eclipseWtpComponent') { task.enabled = false } if (task.name == 'eclipseWtpFacet') { task.enabled = false } } } } configure(javaProjects()) { apply plugin : 'java' apply plugin : 'signing' sourceCompatibility = target targetCompatibility = target configurations { sources javadocs } task sourcesJar(type: Jar) { description = 'Builds Java Sources Jar' from sourceSets.main.java.srcDirs classifier = 'sources' } task javadocJar(type: Jar, dependsOn: javadoc) { description="Builds Javadoc Jar" from "$docsDir/javadoc" classifier = 'javadoc' } jar { metaInf { from rootProject.file('LICENSE.txt') } } artifacts { sources sourcesJar } } project(':svnkit') { dependencies { compile 'de.regnis.q.sequence:sequence-library:1.0.2' compile 'org.tmatesoft.sqljet:sqljet:1.1.3' compile 'net.java.dev.jna:jna:3.4.0' compile 'com.trilead:trilead-ssh2:1.0.0-build215' testCompile 'junit:junit:4.8' } artifacts { maven jar, sourcesJar, javadocJar } } project(':svnkit-javahl16') { dependencies { compile project(path: ':svnkit') compile 'org.apache.subversion:svn-javahl-api:1.7.5' testCompile 'org.apache.subversion:svn-javahl-tests:1.7.5' } artifacts { maven jar, sourcesJar, javadocJar } } project(':svnkit-cli') { dependencies { compile project(path: ':svnkit') } artifacts { maven jar, sourcesJar, javadocJar } } project(':svnkit-dav') { apply plugin: 'war' dependencies { compile project(path: ':svnkit') compile 'javax.servlet:servlet-api:2.5' } artifacts { maven war } } project(':svnkit-test') { dependencies { compile project(path: ':svnkit-cli') } sourcesJar.enabled=false } project(':svnkit-osgi') { sourcesJar.enabled=false artifacts { maven jar } } project(':svnkit-distribution') { configurations { binaries sources scripts osgi } dependencies { binaries project(path: ':svnkit') binaries project(path: ':svnkit-cli') binaries project(path: ':svnkit-javahl16', configuration: 'archives') sources project(path: ':svnkit', configuration: 'sources') sources project(path: ':svnkit-cli', configuration: 'sources') sources project(path: ':svnkit-javahl16', configuration: 'sources') scripts project(path: ':svnkit-cli', configuration: 'scripts') osgi project(path: ':svnkit-osgi', configuration: 'archives') osgi 'com.trilead:trilead-ssh2-osgi:1.0.0-build215' osgi 'org.tmatesoft.sqljet:sqljet-osgi:1.1.3' osgi 'net.java.dev.jna:jna-osgi:3.4.0' } } task publish(dependsOn: [':svnkit-distribution:buildAll']) { enabled = project.hasProperty('to') } << { File toDir = new File(project.properties['to']) delete(toDir) toDir.mkdirs() ant.unzip(src: new File(project(':svnkit-distribution').distsDir, "svnkit-${version}-all.zip"), dest: toDir.absolutePath) { cutdirsmapper(dirs: '1') } ant.chmod(dir: new File(toDir, 'bin').absolutePath, perm: 'ugo+rx', includes: '**/**', excludes: '**/*.bat') }svnkit-1.7.5+dfsg/build.pom.gradle000066400000000000000000000007151177510526000170410ustar00rootroot00000000000000project.ext { packaging = 'jar' pomName = 'SVNKit Library' pomDescription = 'Pure Java Subversion Library' pomUrl = 'http://www.svnkit.com/' licenses = [['name': 'TMate Open Source License (with dual licensing option)', 'url' : 'http://www.svnkit.com/license.html']] scm = ['url': 'http://svn.svnkit.com/repos/svnkit', 'connection': 'scm:svn:http://svn.svnkit.com/repos/svnkit'] developers = [['id' : 'tmate', 'name' : 'TMate Software']] }svnkit-1.7.5+dfsg/gradlew000077500000000000000000000134221177510526000153420ustar00rootroot00000000000000#!/bin/bash ############################################################################## ## ## ## Gradle wrapper script for UN*X ## ## ## ############################################################################## # Uncomment those lines to set JVM options. GRADLE_OPTS and JAVA_OPTS can be used together. # GRADLE_OPTS="$GRADLE_OPTS -Xmx512m" # JAVA_OPTS="$JAVA_OPTS -Xmx512m" GRADLE_APP_NAME=Gradle # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # Attempt to set JAVA_HOME if it's not already set. if [ -z "$JAVA_HOME" ] ; then if $darwin ; then [ -z "$JAVA_HOME" -a -d "/Library/Java/Home" ] && export JAVA_HOME="/Library/Java/Home" [ -z "$JAVA_HOME" -a -d "/System/Library/Frameworks/JavaVM.framework/Home" ] && export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Home" else javaExecutable="`which javac`" [ -z "$javaExecutable" -o "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ] && die "JAVA_HOME not set and cannot find javac to deduce location, please set JAVA_HOME." # readlink(1) is not available as standard on Solaris 10. readLink=`which readlink` [ `expr "$readLink" : '\([^ ]*\)'` = "no" ] && die "JAVA_HOME not set and readlink not available, please set JAVA_HOME." javaExecutable="`readlink -f \"$javaExecutable\"`" javaHome="`dirname \"$javaExecutable\"`" javaHome=`expr "$javaHome" : '\(.*\)/bin'` export JAVA_HOME="$javaHome" fi fi # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVACMD" ] && JAVACMD=`cygpath --unix "$JAVACMD"` [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi STARTER_MAIN_CLASS=org.gradle.wrapper.GradleWrapperMain CLASSPATH=`dirname "$0"`/gradle/wrapper/gradle-wrapper.jar WRAPPER_PROPERTIES=`dirname "$0"`/gradle/wrapper/gradle-wrapper.properties # Determine the Java command to use to start the JVM. if [ -z "$JAVACMD" ] ; then if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi else JAVACMD="java" fi fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi if [ -z "$JAVA_HOME" ] ; then warn "JAVA_HOME environment variable is not set" fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query businessSystem maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add GRADLE_APP_NAME to the JAVA_OPTS as -Xdock:name if $darwin; then JAVA_OPTS="$JAVA_OPTS -Xdock:name=$GRADLE_APP_NAME" # we may also want to set -Xdock:image fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then JAVA_HOME=`cygpath --path --mixed "$JAVA_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi GRADLE_APP_BASE_NAME=`basename "$0"` exec "$JAVACMD" $JAVA_OPTS $GRADLE_OPTS \ -classpath "$CLASSPATH" \ -Dorg.gradle.appname="$GRADLE_APP_BASE_NAME" \ -Dorg.gradle.wrapper.properties="$WRAPPER_PROPERTIES" \ $STARTER_MAIN_CLASS \ "$@" svnkit-1.7.5+dfsg/gradlew.bat000077500000000000000000000045471177510526000161170ustar00rootroot00000000000000@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem ## @rem Gradle startup script for Windows ## @rem ## @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Uncomment those lines to set JVM options. GRADLE_OPTS and JAVA_OPTS can be used together. @rem set GRADLE_OPTS=%GRADLE_OPTS% -Xmx512m @rem set JAVA_OPTS=%JAVA_OPTS% -Xmx512m set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=.\ @rem Find java.exe set JAVA_EXE=java.exe if not defined JAVA_HOME goto init set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. echo. goto end :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set STARTER_MAIN_CLASS=org.gradle.wrapper.GradleWrapperMain set CLASSPATH=%DIRNAME%\gradle\wrapper\gradle-wrapper.jar set WRAPPER_PROPERTIES=%DIRNAME%\gradle\wrapper\gradle-wrapper.properties set GRADLE_OPTS=%JAVA_OPTS% %GRADLE_OPTS% -Dorg.gradle.wrapper.properties="%WRAPPER_PROPERTIES%" @rem Execute Gradle "%JAVA_EXE%" %GRADLE_OPTS% -classpath "%CLASSPATH%" %STARTER_MAIN_CLASS% %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd if not "%OS%"=="Windows_NT" echo 1 > nul | choice /n /c:1 rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit "%ERRORLEVEL%" exit /b "%ERRORLEVEL%" :mainEnd if "%OS%"=="Windows_NT" endlocal :omegasvnkit-1.7.5+dfsg/settings.gradle000066400000000000000000000003111177510526000170000ustar00rootroot00000000000000rootProject.name = 'org.tmatesoft.svnkit' include 'svnkit' include 'svnkit-cli' include 'svnkit-javahl16' include 'svnkit-dav' include 'svnkit-test' include 'svnkit-osgi' include 'svnkit-distribution'svnkit-1.7.5+dfsg/svnkit-cli/000077500000000000000000000000001177510526000160505ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/build.gradle000066400000000000000000000033531177510526000203330ustar00rootroot00000000000000configurations { scripts } project.ext.packageName = 'org.tmatesoft.svn.cli' project.ext.scripts = ['jsvn' : "${packageName}.SVN", 'jsvnadmin' : "${packageName}.SVNAdmin", 'jsvndumpfilter' : "${packageName}.SVNDumpFilter", 'jsvnlook' : "${packageName}.SVNLook", 'jsvnsync' : "${packageName}.SVNSync", 'jsvnversion' : "${packageName}.SVNVersion"] jar << { File scriptsDir = new File(buildDir, 'scripts') scriptsDir.mkdirs() def classpath = [] configurations.compile.files.each { classpath += fullJarName(it) } classpath += jar.archiveName scripts.keySet().each { scriptName -> def mainclassName = scripts[scriptName] copy { from file("src/main/scripts/jsvn") into scriptsDir filter { it = expandClasspath(it, classpath) it = it.replace('@mainclass@', mainclassName) } eachFile { it.name = scriptName } } copy { from file("src/main/scripts/jsvn.bat") into scriptsDir filter { it = expandClasspath(it, classpath) it = it.replace('@mainclass@', mainclassName) } eachFile { it.name = scriptName + '.bat' } } } copy { from file("src/main/scripts/jsvnsetup.openvms") into scriptsDir filter { it = expandClasspath(it, classpath) } } configurations.scripts.artifacts.add(new org.gradle.api.internal.artifacts.publish.DefaultPublishArtifact("svn-cli-scripts", "dir", "dir", null, new Date(), scriptsDir)) }svnkit-1.7.5+dfsg/svnkit-cli/src/000077500000000000000000000000001177510526000166375ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/000077500000000000000000000000001177510526000175635ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/conf/000077500000000000000000000000001177510526000205105ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/conf/logging.properties000066400000000000000000000006161177510526000242570ustar00rootroot00000000000000svnkit.level=FINEST svnkit-network.level=FINEST svnkit-wc.level=FINEST svnkit-cli.level=FINEST handlers = java.util.logging.FileHandler java.util.logging.FileHandler.pattern = ../logs/svnkit.%u.log java.util.logging.FileHandler.limit = 0 java.util.logging.FileHandler.count = 1 java.util.logging.FileHandler.append = true java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormattersvnkit-1.7.5+dfsg/svnkit-cli/src/main/java/000077500000000000000000000000001177510526000205045ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/000077500000000000000000000000001177510526000212735ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/000077500000000000000000000000001177510526000233015ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/000077500000000000000000000000001177510526000241075ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/000077500000000000000000000000001177510526000246565ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/AbstractSVNCommand.java000066400000000000000000000113671177510526000311620ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; import java.text.MessageFormat; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.TreeSet; import org.tmatesoft.svn.cli.svn.SVNOption; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNHashMap; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class AbstractSVNCommand { private static final Comparator DEFAULT_COMMAND_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { AbstractSVNCommand c1 = (AbstractSVNCommand) o1; AbstractSVNCommand c2 = (AbstractSVNCommand) o2; return c1.getName().compareTo(c2.getName()); } }; private static Map ourCommands = new SVNHashMap(); private String myName; private String[] myAliases; private Collection myOptions; private AbstractSVNCommandEnvironment myEnvironment; private Collection myValidOptions; private boolean myIsFailed; public static void registerCommand(AbstractSVNCommand command) { ourCommands.put(command.getName(), command); for (int i = 0; i < command.getAliases().length; i++) { ourCommands.put(command.getAliases()[i], command); } } public static AbstractSVNCommand getCommand(String nameOrAlias) { return (AbstractSVNCommand) ourCommands.get(nameOrAlias); } public static Iterator availableCommands(Comparator comparator) { comparator = comparator == null ? DEFAULT_COMMAND_COMPARATOR : comparator; TreeSet sortedList = new TreeSet(comparator); sortedList.addAll(ourCommands.values()); return sortedList.iterator(); } protected AbstractSVNCommand(String name, String[] aliases) { myName = name; myAliases = aliases == null ? new String[0] : aliases; myOptions = createSupportedOptions(); if (myOptions == null) { myOptions = new LinkedList(); } myValidOptions = new LinkedList(myOptions); myOptions.addAll(getGlobalOptions()); } public boolean isFailed() { return myIsFailed; } public void setFailed(boolean failed) { myIsFailed = failed; } public abstract void run() throws SVNException; protected abstract Collection createSupportedOptions(); protected abstract String getResourceBundleName(); public String getName() { return myName; } public String[] getAliases() { return myAliases; } public Collection getSupportedOptions() { return myOptions; } public Collection getValidOptions() { return myValidOptions; } public abstract Collection getGlobalOptions(); public void init(AbstractSVNCommandEnvironment env) { myEnvironment = env; } protected AbstractSVNCommandEnvironment getEnvironment() { return myEnvironment; } public String getDescription() { ResourceBundle bundle = null; try { bundle = ResourceBundle.getBundle(getResourceBundleName()); } catch (MissingResourceException missing) { missing.printStackTrace(); bundle = null; } if (bundle != null) { try { return bundle.getString(getName() + ".description"); } catch (MissingResourceException missing) {} } return MessageFormat.format("No description has been found for ''{0}'' command.", new Object[] {getName()}); } public boolean isAlias(String alias) { String[] aliases = getAliases(); for (int i = 0; i < aliases.length; i++) { if (aliases[i].equals(alias)) { return true; } } return false; } public boolean isOptionSupported(AbstractSVNOption option) { boolean supported = getSupportedOptions() != null && getSupportedOptions().contains(option); if (!supported) { return option == SVNOption.HELP || option == SVNOption.QUESTION; } return supported; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/AbstractSVNCommandEnvironment.java000066400000000000000000000536331177510526000334110ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.tmatesoft.svn.core.ISVNCanceller; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashSet; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry; import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNBasicClient; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.core.wc2.SvnGetInfo; import org.tmatesoft.svn.core.wc2.SvnInfo; import org.tmatesoft.svn.core.wc2.SvnOperationFactory; import org.tmatesoft.svn.core.wc2.SvnTarget; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class AbstractSVNCommandEnvironment implements ISVNCanceller { private boolean ourIsCancelled; private InputStream myIn; private PrintStream myErr; private PrintStream myOut; private SVNClientManager myClientManager; private DefaultSVNOptions myOptions; private List myArguments; private String myProgramName; private AbstractSVNCommand myCommand; private String myCommandName; protected AbstractSVNCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { myOut = out; myErr = err; myIn = in; myProgramName = programName; } public String getProgramName() { return myProgramName; } public PrintStream getOut() { return myOut; } public PrintStream getErr() { return myErr; } public InputStream getIn() { return myIn; } public SVNClientManager getClientManager() { return myClientManager; } public DefaultSVNOptions getOptions() { return myOptions; } public List getArguments() { return myArguments; } public AbstractSVNCommand getCommand() { return myCommand; } public String getCommandName() { return myCommandName; } public String popArgument() { if (myArguments.isEmpty()) { return null; } return (String) myArguments.remove(0); } protected void setArguments(List newArguments) { myArguments = newArguments; } public void init(SVNCommandLine commandLine) throws SVNException { initCommand(commandLine); initOptions(commandLine); validateOptions(commandLine); } public boolean run() { myCommand.init(this); try { myCommand.run(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().logSevere(SVNLogType.CLIENT, e); SVNErrorMessage err = e.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.CL_INSUFFICIENT_ARGS || err.getErrorCode() == SVNErrorCode.CL_ARG_PARSING_ERROR) { err = err.wrap("Try ''{0} help'' for more info", getProgramName()); } handleError(err); while(err != null) { if (err.getErrorCode() == SVNErrorCode.WC_LOCKED) { getErr().println("svn: run 'jsvn cleanup' to remove locks (type 'jsvn help cleanup' for details)"); break; } err = err.getChildErrorMessage(); } return false; } finally { getOut().flush(); getErr().flush(); } return !myCommand.isFailed(); } protected void initOptions(SVNCommandLine commandLine) throws SVNException { for (Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); initOption(optionValue); } myArguments = new LinkedList(commandLine.getArguments()); } protected abstract void initOption(SVNOptionValue optionValue) throws SVNException; protected void validateOptions(SVNCommandLine commandLine) throws SVNException { for(Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); if (!myCommand.isOptionSupported(optionValue.getOption())) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Subcommand ''{0}'' doesn''t accept option ''{1}''", new Object[] {myCommand.getName(), optionValue.getName()}); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } protected void initCommand(SVNCommandLine commandLine) throws SVNException { myCommandName = getCommandName(commandLine); myCommand = AbstractSVNCommand.getCommand(myCommandName); if (myCommand == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Unknown command ''{0}''", myCommandName); SVNErrorManager.error(err, SVNLogType.CLIENT); } } protected String getCommandName(SVNCommandLine commandLine) throws SVNException { String commandName = commandLine.getCommandName(); return refineCommandName(commandName, commandLine); } protected abstract String refineCommandName(String commandName, SVNCommandLine commandLine) throws SVNException; protected abstract DefaultSVNOptions createClientOptions() throws SVNException; protected abstract ISVNAuthenticationManager createClientAuthenticationManager(); protected abstract String getCommandLineClientName(); public void initClientManager() throws SVNException { myOptions = createClientOptions(); myClientManager = createClientManager(); } public void dispose() { if (myClientManager != null) { myClientManager.dispose(); myClientManager = null; } } public List combineTargets(Collection targets, boolean warnReserved) throws SVNException { List result = new LinkedList(); result.addAll(getArguments()); if (targets != null) { result.addAll(targets); } boolean hasRelativeURLs = false; SVNURL rootURL = null; for (Iterator resultIter = result.iterator(); resultIter.hasNext();) { String target = (String) resultIter.next(); if (isReposRelative(target)) { hasRelativeURLs = true; } } List canonical = new ArrayList(result.size()); targets = new ArrayList(result.size()); for (Iterator iterator = result.iterator(); iterator.hasNext();) { String path = (String) iterator.next(); if (isReposRelative(path)) { targets.add(path); } else { if (SVNCommandUtil.isURL(path)) { path = SVNEncodingUtil.autoURIEncode(path); try { SVNEncodingUtil.assertURISafe(path); } catch (SVNException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "URL '" + path + "' is not properly URI-encoded"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (path.indexOf("/../") >= 0 || path.endsWith("/..")) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "URL '" + path + "' contains '..' element"); SVNErrorManager.error(err, SVNLogType.CLIENT); } path = SVNPathUtil.canonicalizePath(path); } else { path = path.replace(File.separatorChar, '/'); path = SVNPathUtil.canonicalizePath(path); String name = SVNPathUtil.tail(path); if (SVNFileUtil.getAdminDirectoryName().equals(name) || ".svn".equals(name) || "_svn".equals(name)) { if (warnReserved) { getErr().printf("Skipping argument: E%d: '%s' ends in a reserved name\n", SVNErrorCode.RESERVED_FILENAME_SPECIFIED.getCode(), path); } continue; } } if (hasRelativeURLs) { rootURL = checkRootURLOfTarget(rootURL, path); } targets.add(path); } } if (hasRelativeURLs) { if (rootURL == null) { SVNWCClient wcClient = getClientManager().getWCClient(); rootURL = wcClient.getReposRoot(new File("").getAbsoluteFile(), null, SVNRevision.BASE); } for (Iterator targetsIter = targets.iterator(); targetsIter.hasNext();) { String target = (String) targetsIter.next(); if (isReposRelative(target)) { String pegRevisionString = null; int ind = target.indexOf('@'); if (ind != -1) { target = target.substring(0, ind); pegRevisionString = target.substring(ind); } SVNURL targetURL = resolveRepositoryRelativeURL(rootURL, target); target = targetURL.toString(); if (pegRevisionString != null) { target += pegRevisionString; } } canonical.add(target); } } else { canonical.addAll(targets); } return canonical; } public SVNRevision[] parseRevision(String revStr) { Matcher matcher = Pattern.compile("(\\{[^\\}]+\\}|[^:]+)((:)(.*))?").matcher(revStr); matcher.matches(); boolean colon = ":".equals(matcher.group(3)); SVNRevision r1 = SVNRevision.parse(matcher.group(1)); SVNRevision r2 = SVNRevision.parse(matcher.group(4)); return (colon && (r1 == SVNRevision.UNDEFINED || r2 == SVNRevision.UNDEFINED)) || r1 == SVNRevision.UNDEFINED ? null : new SVNRevision[]{r1, r2}; } public byte[] readFromFile(File file) throws SVNException { InputStream is = null; ByteArrayOutputStream bos = null; try { file = file.getAbsoluteFile(); is = SVNFileUtil.openFileForReading(file); bos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; while(true) { int read = is.read(buffer); if (read < 0) { break; } bos.write(buffer, 0, read); } } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } finally { SVNFileUtil.closeFile(is); } return bos != null ? bos.toByteArray() : null; } public void handleError(SVNErrorMessage err) { Collection codes = new SVNHashSet(); int count = 0; while(err != null && count < 3) { SVNErrorCode errorCode = err.getErrorCode(); if ("".equals(err.getMessageTemplate()) && codes.contains(errorCode)) { err = err.hasChildErrorMessage() ? err.getChildErrorMessage() : null; continue; } if ("".equals(err.getMessageTemplate())) { codes.add(errorCode); } Object[] objects = err.getRelatedObjects(); if (objects != null && objects.length > 0) { String template = err.getMessageTemplate(); for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof File) { objects[i] = SVNCommandUtil.getLocalPath(getRelativePath((File) objects[i])); } else if (objects[i] instanceof Number) { objects[i] = objects[i].toString(); } } String message = template; if (objects.length > 0) { try { message = MessageFormat.format(template, objects); } catch (IllegalArgumentException e) { message = template; } } if (err.getType() == SVNErrorMessage.TYPE_WARNING) { String msg = getCommandLineClientName() +": warning: " + (err.isErrorCodeShouldShown() ? "W" + errorCode.getCode() + ": " : "") + message; getErr().println(msg); } else { String msg = getCommandLineClientName() + ": " + (err.isErrorCodeShouldShown() ? "E" + errorCode.getCode() + ": " : "") + message; getErr().println(msg); count++; } } else { getErr().println(err.getMessage()); count++; } err = err.hasChildErrorMessage() ? err.getChildErrorMessage() : null; } } public boolean handleWarning(SVNErrorMessage err, SVNErrorCode[] warningCodes, boolean quiet) throws SVNException { if (err == null) { return true; } SVNErrorCode code = err.getErrorCode(); for (int i = 0; i < warningCodes.length; i++) { if (code == warningCodes[i]) { if (!quiet) { err.setType(SVNErrorMessage.TYPE_WARNING); err.setChildErrorMessage(null); handleError(err); } return false; } } throw new SVNException(err); } public String getRelativePath(File file) { String inPath = file.getAbsolutePath().replace(File.separatorChar, '/'); String basePath = new File("").getAbsolutePath().replace(File.separatorChar, '/'); String commonRoot = getCommonAncestor(inPath, basePath); if (commonRoot != null) { if (equals(inPath , commonRoot)) { return ""; } else if (startsWith(inPath, commonRoot + "/")) { return inPath.substring(commonRoot.length() + 1); } } return inPath; } public SVNURL getURLFromTarget(String target) throws SVNException { if (SVNCommandUtil.isURL(target)) { return SVNURL.parseURIEncoded(target); } try { SvnGetInfo info = new SvnOperationFactory().createGetInfo(); info.setSingleTarget(SvnTarget.fromFile(new File(target))); info.setDepth(SVNDepth.EMPTY); SvnInfo i = info.run(); return i != null ? i.getUrl() : null; } catch (SVNException e) { // } return null; } public boolean isVersioned(String target) throws SVNException { SVNPath commandTarget = new SVNPath(target); if (SVNBasicClient.isWC17Supported()) { SVNWCContext context = null; try { context = new SVNWCContext(getOptions(), null); File file = commandTarget.getFile(); if (file != null) { SVNNodeKind kind = context.readKind(file.getAbsoluteFile(), false); return kind != null && kind != SVNNodeKind.NONE && kind != SVNNodeKind.UNKNOWN; } } catch (SVNException e) { // } finally { if (context != null) { context.close(); } } } else { SVNWCAccess wcAccess = null; try { wcAccess = SVNWCAccess.newInstance(null); wcAccess.probeOpen(commandTarget.getFile(), false, 0); SVNEntry entry = wcAccess.getVersionedEntry(commandTarget.getFile(), false); return entry != null; } catch (SVNException e) { // } finally { if (wcAccess != null) { wcAccess.close(); } } } return false; } public void printCommitInfo(SVNCommitInfo info) { if (info != null && info.getNewRevision() >= 0 && info != SVNCommitInfo.NULL) { getOut().println("\nCommitted revision " + info.getNewRevision() + "."); if (info.getErrorMessage() != null && info.getErrorMessage().isWarning()) { getOut().println("\n" + info.getErrorMessage().getMessage()); } } } private SVNURL resolveRepositoryRelativeURL(SVNURL rootURL, String relativeURL) throws SVNException { if (!isReposRelative(relativeURL)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Improper relative URL ''{0}''", relativeURL); SVNErrorManager.error(err, SVNLogType.CLIENT); } relativeURL = relativeURL.substring(2); SVNURL url = rootURL.appendPath(relativeURL, true); return url; } private SVNURL checkRootURLOfTarget(SVNURL rootURL, String target) throws SVNException { SVNPath svnPath = new SVNPath(target, true); SVNWCClient client = getClientManager().getWCClient(); File path = svnPath.isFile() ? svnPath.getFile() : null; SVNURL url = svnPath.isURL() ? svnPath.getURL() : null; SVNURL tmpRootURL = null; try { tmpRootURL = client.getReposRoot(path, url, svnPath.getPegRevision()); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.ENTRY_NOT_FOUND || err.getErrorCode() == SVNErrorCode.WC_NOT_DIRECTORY) { return rootURL; } throw svne; } if (rootURL != null) { if (!rootURL.equals(tmpRootURL)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "All non-relative targets must have the same root URL"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return rootURL; } return tmpRootURL; } private static boolean isReposRelative(String path) { return path != null && path.startsWith("^/"); } private static boolean startsWith(String p1, String p2) { if (SVNFileUtil.isWindows || SVNFileUtil.isOpenVMS) { return p1.toLowerCase().startsWith(p2.toLowerCase()); } return p1.startsWith(p2); } private static boolean equals(String p1, String p2) { if (SVNFileUtil.isWindows || SVNFileUtil.isOpenVMS) { return p1.toLowerCase().equals(p2.toLowerCase()); } return p1.equals(p2); } private static String getCommonAncestor(String p1, String p2) { if (SVNFileUtil.isWindows || SVNFileUtil.isOpenVMS) { String ancestor = SVNPathUtil.getCommonPathAncestor(p1.toLowerCase(), p2.toLowerCase()); if (equals(ancestor, p1)) { return p1; } else if (equals(ancestor, p2)) { return p2; } else if (startsWith(p1, ancestor)) { return p1.substring(0, ancestor.length()); } return ancestor; } return SVNPathUtil.getCommonPathAncestor(p1, p2); } public void checkCancelled() throws SVNCancelException { synchronized (AbstractSVNCommandEnvironment.class) { if (ourIsCancelled) { SVNErrorManager.cancel("operation cancelled", SVNLogType.CLIENT); } } } public void setCancelled() { synchronized (AbstractSVNCommandEnvironment.class) { ourIsCancelled = true; } } public SVNClientManager createClientManager() { SVNClientManager clientManager = SVNClientManager.newInstance(myOptions, createClientAuthenticationManager()); clientManager.setEventHandler(new ISVNEventHandler() { public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { AbstractSVNCommandEnvironment.this.checkCancelled(); } }); return clientManager; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/AbstractSVNLauncher.java000066400000000000000000000112341177510526000313360ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; import java.text.MessageFormat; import org.tmatesoft.svn.core.SVNAuthenticationException; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class AbstractSVNLauncher { private static volatile boolean ourIsCompleted; private static volatile Thread ourShutdownHook; protected void run(String[] args) { ourIsCompleted = false; if (needArgs() && (args == null || args.length < 1)) { printBasicUsage(); failure(); return; } registerOptions(); registerCommands(); SVNCommandLine commandLine = new SVNCommandLine(needCommand()); try { commandLine.init(args); } catch (SVNException e) { handleError(e); printBasicUsage(); failure(); return; } AbstractSVNCommandEnvironment env = createCommandEnvironment(); synchronized(AbstractSVNLauncher.class) { if (ourShutdownHook == null) { ourShutdownHook = new Thread(new Cancellator(env)); } else { Runtime.getRuntime().removeShutdownHook(ourShutdownHook); } Runtime.getRuntime().addShutdownHook(ourShutdownHook); } try { try { env.init(commandLine); } catch (SVNException e) { handleError(e); if (e instanceof SVNCancelException || e instanceof SVNAuthenticationException) { env.dispose(); failure(); return; } printBasicUsage(); env.dispose(); failure(); return; } env.initClientManager(); if (!env.run()) { env.dispose(); failure(); return; } env.dispose(); success(); } catch (Throwable th) { SVNDebugLog.getDefaultLog().logSevere(SVNLogType.CLIENT, th); th.printStackTrace(); if (env != null) { env.dispose(); } failure(); } finally { setCompleted(); } } protected abstract boolean needArgs(); protected abstract boolean needCommand(); protected abstract String getProgramName(); protected abstract AbstractSVNCommandEnvironment createCommandEnvironment(); protected void printBasicUsage() { System.err.println(MessageFormat.format("Type ''{0} help'' for usage.", new Object[] {getProgramName()})); } protected abstract void registerCommands(); protected abstract void registerOptions(); public void handleError(SVNException e) { System.err.println(e.getMessage()); } public void failure() { setCompleted(); try { System.exit(1); } catch (SecurityException se) { } } public void success() { setCompleted(); try { System.exit(0); } catch (SecurityException se) { } } private void setCompleted() { synchronized (AbstractSVNLauncher.class) { ourIsCompleted = true; AbstractSVNLauncher.class.notifyAll(); } } private class Cancellator implements Runnable { private AbstractSVNCommandEnvironment myEnvironment; public Cancellator(AbstractSVNCommandEnvironment env) { myEnvironment = env; } public void run() { myEnvironment.setCancelled(); synchronized (AbstractSVNLauncher.class) { while(!ourIsCompleted) { try { AbstractSVNLauncher.class.wait(); } catch (InterruptedException e) { } } } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/AbstractSVNOption.java000066400000000000000000000045051177510526000310500ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class AbstractSVNOption { private String myName; private String myAlias; private boolean myIsUnary; protected AbstractSVNOption(String name, String alias, boolean unary) { myName = name; myAlias = alias; myIsUnary = unary; } public String getName() { return myName; } public String getAlias() { return myAlias; } public boolean isUnary() { return myIsUnary; } public String getDescription(AbstractSVNCommand context, String programName) { ResourceBundle bundle = null; try { bundle = ResourceBundle.getBundle(getResourceBundleName()); } catch (MissingResourceException missing) { bundle = null; } if (bundle != null) { String[] keys = context != null ? new String[] {getName() + "." + context.getName(), getAlias() + "." + context.getName(), getName(), getAlias()} : new String[] {getName(), getAlias()}; for (int i = 0; i < keys.length; i++) { String key = keys[i]; if (key == null) { continue; } try { return bundle.getString(key); } catch (MissingResourceException missing) { } } } return MessageFormat.format("not supported by ''{0}''", new Object[]{programName}); } protected abstract String getResourceBundleName(); public String toString() { return getName(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVN.java000066400000000000000000000013461177510526000261730ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVN { public static void main(String[] args) { org.tmatesoft.svn.cli.svn.SVN.main(args); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNAdmin.java000066400000000000000000000013651177510526000271450ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdmin { public static void main(String[] args) { org.tmatesoft.svn.cli.svnadmin.SVNAdmin.main(args); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNCommandLine.java000066400000000000000000000147451177510526000303110ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCommandLine { private static final Map ourOptions = new SVNHashMap(); public static void registerOption(AbstractSVNOption option) { if (option.getName() != null) { ourOptions.put("--" + option.getName(), option); } if (option.getAlias() != null) { ourOptions.put("-" + option.getAlias(), option); } } private String myCommand; private Collection myArguments; private Collection myOptions; private boolean myNeedsCommand; public SVNCommandLine() { this(true); } public SVNCommandLine(boolean needsCommand) { myArguments = new LinkedList(); myOptions = new LinkedList(); myNeedsCommand = needsCommand; } public void init(String[] args) throws SVNException { myInputArguments = args; myArgumentPosition = 0; myArgumentIndex = 0; myArguments = new LinkedList(); myOptions = new LinkedList(); myCommand = null; while (true) { SVNOptionValue value = nextOption(); if (value != null) { myOptions.add(value); } else { return; } } } private int myArgumentIndex; private int myArgumentPosition; private String[] myInputArguments; private SVNOptionValue nextOption() throws SVNException { if (myArgumentPosition == 0) { while (myArgumentIndex < myInputArguments.length && !myInputArguments[myArgumentIndex].startsWith("-")) { String argument = myInputArguments[myArgumentIndex]; // this is either command name or non-option argument. if (myNeedsCommand && myCommand == null) { myCommand = argument; } else { myArguments.add(argument); } myArgumentIndex++; } if (myArgumentIndex >= myInputArguments.length) { return null; } // now we're in the beginning of option. parse option name first. String argument = myInputArguments[myArgumentIndex]; if (argument.startsWith("--")) { // it is long option, long option with '=value', or --long value set. int valueIndex = argument.indexOf('='); String optionName = valueIndex > 0 ? argument.substring(0, valueIndex) : argument; AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName); if (option == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName); SVNErrorManager.error(err, SVNLogType.CLIENT); } String value = null; if (!option.isUnary()) { if (valueIndex > 0) { value = argument.substring(valueIndex + 1); } else { myArgumentIndex++; value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null; } if (value == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName); SVNErrorManager.error(err, SVNLogType.CLIENT); } } myArgumentIndex++; return new SVNOptionValue(option, optionName, value); } myArgumentPosition = 1; } // set of short options or set of short options with '[=]value', or -shortset value // process each option is set until binary one found. then process value. String argument = myInputArguments[myArgumentIndex]; String optionName = "-" + argument.charAt(myArgumentPosition++); AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName); if (option == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName); SVNErrorManager.error(err, SVNLogType.CLIENT); } String value = null; if (!option.isUnary()) { if (myArgumentPosition < argument.length()) { value = argument.substring(myArgumentPosition); if (value.startsWith("=")) { value = value.substring(1); } } else { myArgumentIndex++; value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null; } myArgumentPosition = 0; myArgumentIndex++; if (value == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName); SVNErrorManager.error(err, SVNLogType.CLIENT); } } if (myArgumentPosition >= argument.length()) { myArgumentPosition = 0; myArgumentIndex++; } return new SVNOptionValue(option, optionName, value); } public Iterator optionValues() { return myOptions.iterator(); } public String getCommandName() { return myCommand; } public Collection getArguments() { return myArguments; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNCommandUtil.java000066400000000000000000000575631177510526000303440ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.text.MessageFormat; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import org.tmatesoft.svn.cli.svn.SVNCommandEnvironment; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.ISVNReturnValueCallback; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.util.SVNLogType; import org.tmatesoft.svn.util.Version; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCommandUtil { public static String getLocalPath(String path) { path = path.replace('/', File.separatorChar); if ("".equals(path)) { path = "."; } return path; } public static boolean isURL(String pathOrUrl){ return SVNPathUtil.isURL(pathOrUrl); } public static void mergeFileExternally(AbstractSVNCommandEnvironment env, String basePath, String repositoryPath, String localPath, String mergeResultPath, String wcPath, final boolean[] remainsInConflict) throws SVNException { String[] testEnvironment = SVNFileUtil.getTestEnvironment(); String mergeToolCommand = testEnvironment[1]; if (testEnvironment[1] == null) { mergeToolCommand = SVNFileUtil.getEnvironmentVariable("SVN_MERGE"); if (mergeToolCommand == null) { mergeToolCommand = env.getOptions().getMergeTool(); } testEnvironment = null; } else { mergeToolCommand = testEnvironment[1]; testEnvironment = new String[] {"SVNTEST_EDITOR_FUNC=" + (testEnvironment[2] == null ? "" : testEnvironment[2])}; } if (mergeToolCommand != null) { mergeToolCommand = mergeToolCommand.trim(); if (mergeToolCommand.length() == 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_NO_EXTERNAL_MERGE_TOOL, "The SVN_MERGE environment variable is empty or consists solely of whitespace. Expected a shell command."); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_NO_EXTERNAL_MERGE_TOOL, "The environment variable SVN_MERGE and the merge-tool-cmd run-time configuration option were not set."); SVNErrorManager.error(err, SVNLogType.CLIENT); } String merger = mergeToolCommand; if (SVNFileUtil.isWindows) { merger = mergeToolCommand.toLowerCase(); } ISVNReturnValueCallback runCallback = new ISVNReturnValueCallback() { public void handleChar(char ch) throws SVNException { } public void handleReturnValue(int returnValue) throws SVNException { if (returnValue != 0 && returnValue != 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.EXTERNAL_PROGRAM, "The external merge tool exited with exit code {0}", String.valueOf(returnValue)); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (remainsInConflict != null && remainsInConflict.length > 0) { remainsInConflict[0] = returnValue == 1; } } public boolean isHandleProgramOutput() { return false; } }; runEditor(merger, new String[] { basePath, repositoryPath, localPath, mergeResultPath, wcPath }, testEnvironment, runCallback); } public static void editFileExternally(AbstractSVNCommandEnvironment env, String editorCommand, String path) throws SVNException { editorCommand = getEditorCommand(env, editorCommand); String testEnv[] = SVNFileUtil.getTestEnvironment(); if (testEnv[0] != null) { testEnv = new String[] {"SVNTEST_EDITOR_FUNC=" + (testEnv[2] != null ? testEnv[2] : "")}; } if (testEnv != null) { LinkedList environment = new LinkedList(); for (int i = 0; i < testEnv.length; i++) { if (testEnv[i] != null) { environment.add(testEnv[i]); } } if (!environment.isEmpty()) { testEnv = (String[]) environment.toArray(new String[environment.size()]); } else { testEnv = null; } } final int[] exitCode = { -1 }; ISVNReturnValueCallback procCallback = new ISVNReturnValueCallback() { public void handleChar(char ch) throws SVNException { } public void handleReturnValue(int returnValue) throws SVNException { exitCode[0] = returnValue; } public boolean isHandleProgramOutput() { return false; } }; String result = runEditor(editorCommand, new String[] {path}, testEnv, procCallback); if (result == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.EXTERNAL_PROGRAM, "system(''{0}'') returned {1}", new Object[] { editorCommand + " " + path, String.valueOf(exitCode[0]) }); //SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.EXTERNAL_PROGRAM, "Editor command '" + // editorCommand + " " + path + "' failed."); SVNErrorManager.error(err, SVNLogType.CLIENT); } } public static byte[] runEditor(AbstractSVNCommandEnvironment env, String editorCommand, byte[] existingValue, String prefix) throws SVNException { File tmpDir = new File(System.getProperty("java.io.tmpdir")); File tmpFile = SVNFileUtil.createUniqueFile(tmpDir, prefix, ".tmp", false); OutputStream os = null; try { os = SVNFileUtil.openFileForWriting(tmpFile); os.write(existingValue); } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } finally { SVNFileUtil.closeFile(os); } SVNFileUtil.setLastModified(tmpFile, System.currentTimeMillis() - 2000); long timestamp = tmpFile.lastModified(); editorCommand = getEditorCommand(env, editorCommand); String[] testEnv = SVNFileUtil.getTestEnvironment(); if (testEnv[0] != null) { testEnv = new String[] {"SVNTEST_EDITOR_FUNC=" + (testEnv[2] != null ? testEnv[2] : "")}; } else { testEnv = null; } try { String result = runEditor(editorCommand, new String[] {tmpFile.getAbsolutePath()}, testEnv, null); if (result == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Editor command '" + editorCommand + " " + tmpFile.getAbsolutePath() + "' failed."); SVNErrorManager.error(err, SVNLogType.CLIENT); } // now read from file. if (timestamp == tmpFile.lastModified()) { return null; } InputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; try { is = SVNFileUtil.openFileForReading(tmpFile); while(true) { int read = is.read(buffer); if (read < 0) { break; } bos.write(buffer, 0, read); } } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } finally { SVNFileUtil.closeFile(is); } return bos.toByteArray(); } finally { SVNFileUtil.deleteFile(tmpFile); } } private static String runEditor(String editorCommand, String[] args, String[] env, ISVNReturnValueCallback callback) throws SVNException { String result = null; if (SVNFileUtil.isWindows || SVNFileUtil.isOS2) { String editor = editorCommand.trim().toLowerCase(); if (!(editor.endsWith(".exe") || editor.endsWith(".bat") || editor.endsWith(".cmd"))) { String[] command = new String[3 + args.length]; command[0] = "cmd.exe"; command[1] = "/C"; command[2] = editorCommand; for (int i = 0; i < args.length; i++) { command[3 + i] = args[i]; } result = SVNFileUtil.execCommand(command, env, false, callback); } else { String[] command = new String[1 + args.length]; command[0] = editorCommand; for (int i = 0; i < args.length; i++) { command[1 + i] = args[i]; } result = SVNFileUtil.execCommand(command, env, false, callback); } } else if (SVNFileUtil.isLinux || SVNFileUtil.isBSD || SVNFileUtil.isOSX || SVNFileUtil.isSolaris){ if (env == null && !SVNFileUtil.isSolaris) { String shellCommand = SVNFileUtil.getEnvironmentVariable("SHELL"); if (shellCommand == null || "".equals(shellCommand.trim())) { shellCommand = "/bin/sh"; } String[] command = new String[3]; command[0] = shellCommand; command[1] = "-c"; command[2] = editorCommand; for (int i = 0; i < args.length; i++) { command[2] += " " + args[i]; } command[2] += " < /dev/tty > /dev/tty"; result = SVNFileUtil.execCommand(command, env, false, callback); } else { // test mode, do not use bash and redirection. String[] command = new String[1 + args.length]; command[0] = editorCommand; for (int i = 0; i < args.length; i++) { command[1 + i] = args[i]; } result = SVNFileUtil.execCommand(command, env, false, callback); } } else if (SVNFileUtil.isOpenVMS) { String[] command = new String[1 + args.length]; command[0] = editorCommand; for (int i = 0; i < args.length; i++) { command[1 + i] = args[i]; } result = SVNFileUtil.execCommand(command, env, false, callback); } return result; } public static String prompt(String promptMessage, SVNCommandEnvironment env) throws SVNException { System.err.print(promptMessage); System.err.flush(); String input = null; InputReader reader = new InputReader(System.in); Thread readerThread = new Thread(reader); readerThread.setDaemon(true); readerThread.start(); while (true) { env.checkCancelled(); if (reader.myIsFinished) { input = reader.getReadInput(); break; } try { Thread.sleep(1); } catch (InterruptedException e) { } } if (reader.getError() != null) { SVNErrorManager.error(reader.getError(), SVNLogType.CLIENT); } if (input == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Can't read stdin: End of file found"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return input; } private static String getEditorCommand(AbstractSVNCommandEnvironment env, String editorCommand) throws SVNException { if (editorCommand != null) { return editorCommand; } String[] testEnvironment = SVNFileUtil.getTestEnvironment(); String command = testEnvironment[0]; if (command == null) { command = SVNFileUtil.getEnvironmentVariable("SVN_EDITOR"); if (command == null) { command = env.getOptions().getEditor(); } if (command == null) { command = SVNFileUtil.getEnvironmentVariable("VISUAL"); } if (command == null) { command = SVNFileUtil.getEnvironmentVariable("EDITOR"); } } String errorMessage = null; if (command == null) { errorMessage = "None of the environment variables SVN_EDITOR, VISUAL or EDITOR is " + "set, and no 'editor-cmd' run-time configuration option was found"; } else if ("".equals(command.trim())) { errorMessage = "The EDITOR, SVN_EDITOR or VISUAL environment variable or " + "'editor-cmd' run-time configuration option is empty or " + "consists solely of whitespace. Expected a shell command."; } if (errorMessage != null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_NO_EXTERNAL_EDITOR, errorMessage), SVNLogType.CLIENT); } return command; } public static int getLinesCount(String str) { if ("".equals(str)) { return 1; } int count = 1; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '\r') { count++; if (i < str.length() - 1 && str.charAt(i + 1) == '\n') { i++; } } else if (str.charAt(i) == '\n') { count++; } } if (count == 0) { count++; } return count; } public static String[] breakToLines(String str) { if (str == null) { return null; } if ("".equals(str)) { return new String[] { "" }; } LinkedList list = new LinkedList(); int i = 0; int start = 0; for (; i < str.length(); i++) { char ch = str.charAt(i); if (ch == '\r' || ch == '\n') { if (i < str.length() - 1) { char nextCh = str.charAt(i + 1); if ((ch == '\r' && nextCh == '\n') || (ch == '\n' && nextCh == '\r')) { i++; } list.add(str.substring(start, i + 1)); } else { list.add(str.substring(start, i + 1)); } start = i + 1; } } if (start != i) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } public static String getCommandHelp(AbstractSVNCommand command, String programName, boolean printOptionAlias) { StringBuffer help = new StringBuffer(); help.append(command.getName()); if (command.getAliases().length > 0) { help.append(" ("); for (int i = 0; i < command.getAliases().length; i++) { help.append(command.getAliases()[i]); if (i + 1 < command.getAliases().length) { help.append(", "); } } help.append(")"); } if (!"".equals(command.getName())) { help.append(": "); } help.append(command.getDescription()); if (!command.getSupportedOptions().isEmpty()) { help.append("\n"); if (!command.getValidOptions().isEmpty()) { help.append("\nValid options:\n"); for (Iterator options = command.getValidOptions().iterator(); options.hasNext();) { AbstractSVNOption option = (AbstractSVNOption) options.next(); help.append(" "); String optionDesc = null; if (option.getAlias() != null && printOptionAlias) { optionDesc = "-" + option.getAlias() + " [--" + option.getName() + "]"; } else { optionDesc = "--" + option.getName(); } if (!option.isUnary()) { optionDesc += " ARG"; } int chars = optionDesc.length() < 24 ? 24 : optionDesc.length(); help.append(SVNFormatUtil.formatString(optionDesc, chars, true)); help.append(" : "); help.append(option.getDescription(command, programName)); help.append("\n"); } } if (!command.getGlobalOptions().isEmpty()) { help.append("\nGlobal options:\n"); for (Iterator options = command.getGlobalOptions().iterator(); options.hasNext();) { AbstractSVNOption option = (AbstractSVNOption) options.next(); help.append(" "); String optionDesc = null; if (option.getAlias() != null) { optionDesc = "-" + option.getAlias() + " [--" + option.getName() + "]"; } else { optionDesc = "--" + option.getName(); } if (!option.isUnary()) { optionDesc += " ARG"; } help.append(SVNFormatUtil.formatString(optionDesc, 24, true)); help.append(" : "); help.append(option.getDescription(command, programName)); help.append("\n"); } } } return help.toString(); } public static String getVersion(AbstractSVNCommandEnvironment env, boolean quiet) { String version = Version.getShortVersionString(); String revNumber = Version.getRevisionString() == null ? "SNAPSHOT" : Version.getRevisionString(); String message = MessageFormat.format(env.getProgramName() + ", version {0}\n", new Object[] {version + " (" + revNumber + ")"}); if (quiet) { message = version; } if (!quiet) { message += "\nCopyright (c) 2004-2012 TMate Software.\n" + "SVNKit is an Open Source software, see http://svnkit.com/ for more information.\n" + "SVNKit is a pure Java (TM) version of Subversion, see http://subversion.tigris.org/"; } return message; } public static String getGenericHelp(String programName, String header, String footer, Comparator commandComparator) { StringBuffer help = new StringBuffer(); if (header != null) { String version = Version.getShortVersionString(); header = MessageFormat.format(header, new Object[] {programName, version}); help.append(header); } for (Iterator commands = AbstractSVNCommand.availableCommands(commandComparator); commands.hasNext();) { AbstractSVNCommand command = (AbstractSVNCommand) commands.next(); help.append("\n "); help.append(command.getName()); if (command.getAliases().length > 0) { help.append(" ("); for (int i = 0; i < command.getAliases().length; i++) { help.append(command.getAliases()[i]); if (i + 1 < command.getAliases().length) { help.append(", "); } } help.append(")"); } } help.append("\n\n"); if (footer != null) { help.append(footer); } return help.toString(); } public static void parseConfigOption(String optionArg, Map configOptions, Map serversOptions) throws SVNException { if (optionArg != null) { int firstColonInd = optionArg.indexOf(':'); if (firstColonInd != -1 && firstColonInd != optionArg.length() - 1) { int secondColonInd = optionArg.indexOf(':', firstColonInd + 1); if (secondColonInd != -1 && secondColonInd != firstColonInd + 1) { int equalsSignInd = optionArg.indexOf('=', secondColonInd + 1); if (equalsSignInd != -1 && equalsSignInd != secondColonInd + 1) { String fileName = optionArg.substring(0, firstColonInd); String section = optionArg.substring(firstColonInd + 1, secondColonInd); String option = optionArg.substring(secondColonInd + 1, equalsSignInd); if (option.indexOf(':') == -1) { String value = optionArg.substring(equalsSignInd + 1); Map options = null; if ("servers".equals(fileName)) { options = serversOptions; } else if ("config".equals(fileName)) { options = configOptions; } if (options != null) { Map values = (Map) options.get(section); if (values == null) { values = new HashMap(); options.put(section, values); } values.put(option, value); return; } } } } } } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Invalid syntax of argument of --config-option"); SVNErrorManager.error(err, SVNLogType.CLIENT); } private static class InputReader implements Runnable { private BufferedReader myReader; private String myReadInput; private SVNErrorMessage myError; volatile boolean myIsFinished; public InputReader(InputStream is) { myReader = new BufferedReader(new InputStreamReader(is)); } public void run() { myIsFinished = false; try { myReadInput = myReader.readLine(); } catch (IOException e) { myError = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Can''t read stdin: {0}", e.getLocalizedMessage()); } myIsFinished = true; } public String getReadInput() { return myReadInput; } public SVNErrorMessage getError() { return myError; } } } SVNConsoleAuthenticationProvider.java000066400000000000000000000540511177510526000340530ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.cert.X509Certificate; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.auth.SVNSSHAuthentication; import org.tmatesoft.svn.core.auth.SVNSSLAuthentication; import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication; import org.tmatesoft.svn.core.internal.util.SVNSSLUtil; import org.tmatesoft.svn.core.internal.wc.ISVNAuthStoreHandler; import org.tmatesoft.svn.core.internal.wc.ISVNGnomeKeyringPasswordProvider; import org.tmatesoft.svn.core.internal.wc.ISVNSSLPasspharsePromptSupport; import org.tmatesoft.svn.core.wc.SVNWCUtil; /** * @version 1.0 * @author TMate Software Ltd. */ public class SVNConsoleAuthenticationProvider implements ISVNAuthenticationProvider, ISVNSSLPasspharsePromptSupport, ISVNAuthStoreHandler, ISVNGnomeKeyringPasswordProvider { private static final String OUR_PASSPHRASE_PROMPT_TEXT = "-----------------------------------------------------------------------\n" + "ATTENTION! Your passphrase for client certificate:\n" + "\n" + " {0}\n" + "\n" + "can only be stored to disk unencrypted! You are advised to configure\n" + "your system so that Subversion can store passphrase encrypted, if\n" + "possible. See the documentation for details.\n" + "\n" + "You can avoid future appearances of this warning by setting the value\n" + "of the ''store-ssl-client-cert-pp-plaintext'' option to either ''yes'' or\n" + "''no'' in ''{1}''.\n" + "-----------------------------------------------------------------------\n"; private static final String OUR_PASSWORD_PROMPT_TEXT = "-----------------------------------------------------------------------\n" + "ATTENTION! Your password for authentication realm:\n" + "\n" + " {0}\n" + "\n" + "can only be stored to disk unencrypted! You are advised to configure\n" + "your system so that Subversion can store passwords encrypted, if\n" + "possible. See the documentation for details.\n" + "\n" + "You can avoid future appearances of this warning by setting the value\n" + "of the ''store-plaintext-passwords'' option to either ''yes'' or ''no'' in\n" + "''{1}''.\n" + "-----------------------------------------------------------------------\n"; private static final String OUR_HOST_KEY_PROMPT_TEXT = "The ''{0}'' server''s key fingerprint is:\n{1}\n"; private static final String OUR_PASSWORD_PROMPT_STRING = "Store password unencrypted (yes/no)? "; private static final String OUR_PASSPHRASE_PROMPT_STRING = "Store passphrase unencrypted (yes/no)? "; private static final int MAX_PROMPT_COUNT = 3; private Map myRequestsCount = new HashMap(); private boolean myIsTrustServerCertificate; public SVNConsoleAuthenticationProvider(boolean trustServerCertificate) { myIsTrustServerCertificate = trustServerCertificate; } public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) { if (certificate instanceof byte[]) { StringBuffer prompt = new StringBuffer(OUR_HOST_KEY_PROMPT_TEXT); if (resultMayBeStored) { prompt.append("If you trust this host, enter ''p'' to add the key to the SVN cache and carry on connecting.\n"); prompt.append("If you want to carry on connecting just once, without adding the key to the cache, type ''t''."); prompt.append("If you do not trust this host, type ''R'' to abandon the connection."); prompt.append("\n(R)eject, accept (t)emporarily or accept (p)ermanently? "); } else { prompt.append("If you want to carry on connecting just once, without adding the key to the cache, type ''t''."); prompt.append("If you do not trust this host, type ''R'' to abandon the connection."); prompt.append("\n(R)eject or accept (t)emporarily? "); } System.err.print(MessageFormat.format(prompt.toString(), new Object[] {url.getHost(), SVNSSLUtil.getFingerprint((byte[]) certificate, "MD5")})); System.err.flush(); while(true) { String line = readLine(); if (line == null) { return ISVNAuthenticationProvider.REJECTED; } if (line.length() < 1) { continue; } char ch = line.charAt(0); if (ch == 'R' || ch == 'r') { return ISVNAuthenticationProvider.REJECTED; } else if (ch == 't' || ch == 'T') { return ISVNAuthenticationProvider.ACCEPTED_TEMPORARY; } else if (resultMayBeStored && (ch == 'p' || ch == 'P')) { return ISVNAuthenticationProvider.ACCEPTED; } } } if (myIsTrustServerCertificate) { return ISVNAuthenticationProvider.ACCEPTED_TEMPORARY; } if (!(certificate instanceof X509Certificate)) { return ISVNAuthenticationProvider.ACCEPTED_TEMPORARY; } String hostName = url.getHost(); X509Certificate cert = (X509Certificate) certificate; StringBuffer prompt = SVNSSLUtil.getServerCertificatePrompt(cert, realm, hostName); if (resultMayBeStored) { prompt.append("\n(R)eject, accept (t)emporarily or accept (p)ermanently? "); } else { prompt.append("\n(R)eject or accept (t)emporarily? "); } System.err.print(prompt.toString()); System.err.flush(); while(true) { String line = readLine(); if (line == null) { return ISVNAuthenticationProvider.REJECTED; } if (line.length() < 1) { continue; } char ch = line.charAt(0); if (ch == 'R' || ch == 'r') { return ISVNAuthenticationProvider.REJECTED; } else if (ch == 't' || ch == 'T') { return ISVNAuthenticationProvider.ACCEPTED_TEMPORARY; } else if (resultMayBeStored && (ch == 'p' || ch == 'P')) { return ISVNAuthenticationProvider.ACCEPTED; } } } public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) { Integer requestsCount = (Integer) myRequestsCount.get(kind + "$" + url + "$" + realm); if (requestsCount == null) { myRequestsCount.put(kind + "$" + url + "$" + realm, new Integer(1)); } else if (requestsCount.intValue() == MAX_PROMPT_COUNT) { // no more than three requests per realm return null; } else { myRequestsCount.put(kind + "$" + url + "$" + realm, new Integer(requestsCount.intValue() + 1)); } if (ISVNAuthenticationManager.PASSWORD.equals(kind)) { String name = null; String defaultUserName = null; if (previousAuth != null) { if (previousAuth.isPartial()) { name = previousAuth.getUserName(); } else if (previousAuth.getUserName() != null) { defaultUserName = previousAuth.getUserName(); } } printRealm(realm); if (name == null) { String promptString = defaultUserName == null ? "Username" : "Username [" + defaultUserName + "]"; name = prompt(promptString); if ("".equals(name) && defaultUserName != null) { name = defaultUserName; } } if (name == null) { return null; } String password = promptPassword("Password for '" + name + "'"); if (password == null) { return null; } return new SVNPasswordAuthentication(name, password, authMayBeStored, url, false); } else if (ISVNAuthenticationManager.SSH.equals(kind)) { String name = null; String defaultUserName = null; String defaultPassword = null; String defaultPassphrase = null; File defaultPrivateKeyFile = null; int defaultPort = -1; if (url.getUserInfo() != null && !"".equals(url.getUserInfo())) { defaultUserName = url.getUserInfo(); } if (previousAuth != null && previousAuth instanceof SVNSSHAuthentication) { SVNSSHAuthentication sshPreviousAuth = (SVNSSHAuthentication) previousAuth; defaultUserName = defaultUserName == null ? sshPreviousAuth.getUserName() : defaultUserName; defaultPassword = sshPreviousAuth.getPassword(); defaultPassphrase = sshPreviousAuth.getPassphrase(); defaultPrivateKeyFile = sshPreviousAuth.getPrivateKeyFile(); defaultPort = sshPreviousAuth.getPortNumber(); } printRealm(realm); name = prompt(defaultUserName == null ? "Username" : "Username [" + defaultUserName + "]"); if ("".equals(name) && defaultUserName != null) { name = defaultUserName; } if (name == null) { return null; } String passwordPrompt = null; if (defaultPassword != null) { passwordPrompt = "Password for '" + url.getHost() + "' (leave blank if you are going to use private key) ["; for (int i = 0; i < defaultPassword.length(); i++) { passwordPrompt += "*"; } passwordPrompt += "]"; } else { passwordPrompt = "Password for '" + url.getHost() + "' (leave blank if you are going to use private key)"; } String password = promptPassword(passwordPrompt); if (password == null) { return null; } else if ("".equals(password)) { if (defaultPassword != null) { password = defaultPassword; } else { password = null; } } String keyFilePath = null; File keyFile = null; String passphrase = null; if (password == null) { while(keyFilePath == null) { String privateKeyFilePrompt = null; if (defaultPrivateKeyFile != null) { privateKeyFilePrompt = "Private key for '" + url.getHost() + "' (OpenSSH format) [" + defaultPrivateKeyFile.getAbsolutePath() + "]"; } else { privateKeyFilePrompt = "Private key for '" + url.getHost() + "' (OpenSSH format)"; } keyFilePath = prompt(privateKeyFilePrompt); if ("".equals(keyFilePath)) { if (defaultPrivateKeyFile != null) { if (!defaultPrivateKeyFile.isFile() || !defaultPrivateKeyFile.canRead()) { defaultPrivateKeyFile = null; keyFilePath = null; keyFile = null; continue; } keyFile = defaultPrivateKeyFile; keyFilePath = keyFile.getAbsolutePath(); } continue; } if (keyFilePath == null) { return null; } keyFile = new File(keyFilePath); if (!keyFile.isFile() || !keyFile.canRead()) { keyFilePath = null; keyFile = null; continue; } } String passphrasePrompt = null; if (defaultPassphrase != null) { passphrasePrompt = "Private key passphrase ["; for (int i = 0; i < defaultPassphrase.length(); i++) { passphrasePrompt += "*"; } passphrasePrompt += "]"; } else { passphrasePrompt = "Private key passphrase [none]"; } passphrase = promptPassword(passphrasePrompt); if ("".equals(passphrase)) { if (defaultPassphrase != null) { passphrase = defaultPassphrase; } else { passphrase = null; } } else if (passphrase == null) { return null; } } int port = defaultPort > 0 ? defaultPort : 22; String portValue = prompt("Port number for '" + url.getHost() + "' [" + port + "]"); if (portValue == null) { return null; } if (!"".equals(portValue)) { try { port = Integer.parseInt(portValue); } catch (NumberFormatException e) {} } if (password != null) { return new SVNSSHAuthentication(name, password, port, authMayBeStored, url, false); } else if (keyFile != null) { return new SVNSSHAuthentication(name, keyFile, passphrase, port, authMayBeStored, url, false); } } else if (ISVNAuthenticationManager.USERNAME.equals(kind)) { String name = System.getProperty("user.name"); if (name != null && "".equals(name.trim())) { name = null; } if (name != null) { return new SVNUserNameAuthentication(name, authMayBeStored, url, false); } printRealm(realm); name = prompt(!"file".equals(url.getProtocol()) ? "Author name [" + System.getProperty("user.name") + "]" : "Username [" + System.getProperty("user.name") + "]"); if (name == null) { return null; } if ("".equals(name.trim())) { name = System.getProperty("user.name"); } return new SVNUserNameAuthentication(name, authMayBeStored, url, false); } else if (ISVNAuthenticationManager.SSL.equals(kind)) { if (SVNSSLAuthentication.isCertificatePath(realm)) { String passphrase = promptPassword("Passphrase for '" + realm + "'"); if (passphrase == null) { return null; } return new SVNPasswordAuthentication("", passphrase, authMayBeStored, url, false); } boolean isMSCAPI = false; printRealm(realm); String path = null; while(path == null) { path = prompt("Client certificate filename or 'MSCAPI'"); if ("".equals(path)) { continue; } if (path == null) { return null; } if (path.startsWith(SVNSSLAuthentication.MSCAPI)) { isMSCAPI = true; } else { File file = new File(path); if (!file.isFile() || !file.canRead()) { path = null; continue; } } } if (isMSCAPI) { String alias = promptPassword("MSCAPI certificate alias"); if (alias == null) { return null; } else if ("".equals(alias)) { alias = null; } return new SVNSSLAuthentication(SVNSSLAuthentication.MSCAPI, alias, authMayBeStored, url, false); } SVNSSLAuthentication sslAuth = new SVNSSLAuthentication(new File(path), null, authMayBeStored, url, false); sslAuth.setCertificatePath(path); return sslAuth; } return null; } public boolean canStorePlainTextPasswords(String realm, SVNAuthentication auth) throws SVNException { return isPlainTextAllowed(realm, OUR_PASSWORD_PROMPT_TEXT, OUR_PASSWORD_PROMPT_STRING); } public boolean canStorePlainTextPassphrases(String realm, SVNAuthentication auth) throws SVNException { return isPlainTextAllowed(realm, OUR_PASSPHRASE_PROMPT_TEXT, OUR_PASSPHRASE_PROMPT_STRING); } private boolean isPlainTextAllowed(String realm, String promptText, String promptString) { File configPath = new File(SVNWCUtil.getDefaultConfigurationDirectory(), "servers"); String formattedMessage = MessageFormat.format(promptText, new Object[] { realm, configPath.getAbsolutePath() }); System.err.print(formattedMessage); while (true) { System.err.print(promptString); System.err.flush(); String answer = readLine(); if ("yes".equalsIgnoreCase(answer)) { return true; } else if ("no".equalsIgnoreCase(answer)) { return false; } promptString = "Please type 'yes' or 'no': "; } } private static void printRealm(String realm) { if (realm != null) { System.err.println("Authentication realm: " + realm); System.err.flush(); } } private static String prompt(String label) { System.err.print(label + ": "); System.err.flush(); return readLine(); } private static String promptPassword(String label) { System.err.print(label + ": "); System.err.flush(); Class systemClass = System.class; try { // try to use System.console().readPassword - since JDK 1.6 Method consoleMethod = systemClass.getMethod("console", new Class[0]); if (consoleMethod != null) { Object consoleObject = consoleMethod.invoke(null, new Object[0]); if (consoleObject != null) { Class consoleClass = consoleObject.getClass(); Method readPasswordMethod = consoleClass.getMethod("readPassword", new Class[0]); if (readPasswordMethod != null) { Object password = readPasswordMethod.invoke(consoleObject, new Object[0]); if (password == null) { return null; } else if (password instanceof char[]) { return new String((char[]) password); } } } } } catch (SecurityException e) { } catch (NoSuchMethodException e) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return readLine(); } private static String readLine() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { return reader.readLine(); } catch (IOException e) { return null; } } public boolean isSSLPassphrasePromtSupported() { return true; } public String getKeyringPassword(String keyringName) throws SVNException { return promptPassword("Password for '" + keyringName + "' GNOME keyring"); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNDumpFilter.java000066400000000000000000000014041177510526000301620ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDumpFilter { public static void main(String[] args) { org.tmatesoft.svn.cli.svndumpfilter.SVNDumpFilter.main(args); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNLook.java000066400000000000000000000013621177510526000270160ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLook { public static void main(String[] args) { org.tmatesoft.svn.cli.svnlook.SVNLook.main(args); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNOptionValue.java000066400000000000000000000025041177510526000303560ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNOptionValue { private String myName; private String myValue; private AbstractSVNOption myOption; public SVNOptionValue(AbstractSVNOption option, String name) { this(option, name, null); } public SVNOptionValue(AbstractSVNOption option, String name, String value) { myOption = option; myValue = value; myName = name; } public AbstractSVNOption getOption() { return myOption; } public String getValue() { return myValue; } public String getName() { return myName; } public String toString() { return myOption.getName() + (myValue != null ? (" = " + myValue) : ""); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNSync.java000066400000000000000000000013621177510526000270260ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNSync { public static void main(String[] args) { org.tmatesoft.svn.cli.svnsync.SVNSync.main(args); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/SVNVersion.java000066400000000000000000000013731177510526000275410ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNVersion { public static void main(String[] args) { org.tmatesoft.svn.cli.svnversion.SVNVersion.main(args); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/000077500000000000000000000000001177510526000254645ustar00rootroot00000000000000DefaultSVNCommandLineDiffGenerator.java000066400000000000000000000043331177510526000347750ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.wc.DefaultSVNDiffGenerator; /** * @version 1.3 * @author TMate Software Ltd. */ public class DefaultSVNCommandLineDiffGenerator extends DefaultSVNDiffGenerator { private File myFile1; private File myFile2; public DefaultSVNCommandLineDiffGenerator(File file1, File file2) { myFile1 = file1; myFile2 = file2; } protected void displayHeaderFields(OutputStream os, String label1, String label2) throws IOException { Date time1 = new Date(myFile1.lastModified()); Date time2 = new Date(myFile2.lastModified()); String timestamp1 = SVNDate.formatConsoleDiffDate(time1); String timestamp2 = SVNDate.formatConsoleDiffDate(time2); String file1 = myFile1.getAbsolutePath(); String file2 = myFile2.getAbsolutePath(); os.write("--- ".getBytes(getEncoding())); os.write(file1.getBytes(getEncoding())); os.write("\t".getBytes(getEncoding())); os.write(timestamp1.getBytes(getEncoding())); os.write(getEOL()); os.write("+++ ".getBytes(getEncoding())); os.write(file2.getBytes(getEncoding())); os.write("\t".getBytes(getEncoding())); os.write(timestamp2.getBytes(getEncoding())); os.write(getEOL()); } protected boolean displayHeader(OutputStream os, String path, boolean deleted) throws IOException { return false; } protected boolean isHeaderForced(File file1, File file2) { return false; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVN.java000066400000000000000000000174221177510526000270030ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNLauncher; import org.tmatesoft.svn.cli.SVNCommandLine; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVN extends AbstractSVNLauncher { public static void main(String[] args) { new SVN().run(args); } protected String getProgramName() { return "jsvn"; } protected AbstractSVNCommandEnvironment createCommandEnvironment() { return new SVNCommandEnvironment(getProgramName(), System.out, System.err, System.in); } protected void registerCommands() { AbstractSVNCommand.registerCommand(new SVNAddCommand()); AbstractSVNCommand.registerCommand(new SVNBlameCommand()); AbstractSVNCommand.registerCommand(new SVNCatCommand()); AbstractSVNCommand.registerCommand(new SVNChangeListCommand()); AbstractSVNCommand.registerCommand(new SVNCheckoutCommand()); AbstractSVNCommand.registerCommand(new SVNCleanupCommand()); AbstractSVNCommand.registerCommand(new SVNCommitCommand()); AbstractSVNCommand.registerCommand(new SVNCopyCommand()); AbstractSVNCommand.registerCommand(new SVNDeleteCommand()); AbstractSVNCommand.registerCommand(new SVNDiffCommand()); AbstractSVNCommand.registerCommand(new SVNExportCommand()); AbstractSVNCommand.registerCommand(new SVNHelpCommand()); AbstractSVNCommand.registerCommand(new SVNImportCommand()); AbstractSVNCommand.registerCommand(new SVNInfoCommand()); AbstractSVNCommand.registerCommand(new SVNListCommand()); AbstractSVNCommand.registerCommand(new SVNLockCommand()); AbstractSVNCommand.registerCommand(new SVNLogCommand()); AbstractSVNCommand.registerCommand(new SVNMergeCommand()); AbstractSVNCommand.registerCommand(new SVNMkDirCommand()); AbstractSVNCommand.registerCommand(new SVNMoveCommand()); AbstractSVNCommand.registerCommand(new SVNPropDelCommand()); AbstractSVNCommand.registerCommand(new SVNPropEditCommand()); AbstractSVNCommand.registerCommand(new SVNPropGetCommand()); AbstractSVNCommand.registerCommand(new SVNPropListCommand()); AbstractSVNCommand.registerCommand(new SVNPropSetCommand()); AbstractSVNCommand.registerCommand(new SVNResolveCommand()); AbstractSVNCommand.registerCommand(new SVNResolvedCommand()); AbstractSVNCommand.registerCommand(new SVNStatusCommand()); AbstractSVNCommand.registerCommand(new SVNSwitchCommand()); AbstractSVNCommand.registerCommand(new SVNRevertCommand()); AbstractSVNCommand.registerCommand(new SVNUnLockCommand()); AbstractSVNCommand.registerCommand(new SVNUpdateCommand()); AbstractSVNCommand.registerCommand(new SVNMergeInfoCommand()); AbstractSVNCommand.registerCommand(new SVNPatchCommand()); AbstractSVNCommand.registerCommand(new SVNUpgradeCommand()); } protected void registerOptions() { SVNCommandLine.registerOption(SVNOption.VERBOSE); SVNCommandLine.registerOption(SVNOption.UPDATE); SVNCommandLine.registerOption(SVNOption.NON_RECURSIVE); SVNCommandLine.registerOption(SVNOption.DEPTH); SVNCommandLine.registerOption(SVNOption.SET_DEPTH); SVNCommandLine.registerOption(SVNOption.QUIET); SVNCommandLine.registerOption(SVNOption.NO_IGNORE); SVNCommandLine.registerOption(SVNOption.INCREMENTAL); SVNCommandLine.registerOption(SVNOption.XML); SVNCommandLine.registerOption(SVNOption.CONFIG_DIR); SVNCommandLine.registerOption(SVNOption.IGNORE_EXTERNALS); SVNCommandLine.registerOption(SVNOption.IGNORE_KEYWORDS); SVNCommandLine.registerOption(SVNOption.CHANGELIST); SVNCommandLine.registerOption(SVNOption.HELP); SVNCommandLine.registerOption(SVNOption.QUESTION); SVNCommandLine.registerOption(SVNOption.VERSION); SVNCommandLine.registerOption(SVNOption.RECURSIVE); SVNCommandLine.registerOption(SVNOption.REVISION); SVNCommandLine.registerOption(SVNOption.CHANGE); SVNCommandLine.registerOption(SVNOption.REVPROP); SVNCommandLine.registerOption(SVNOption.STRICT); SVNCommandLine.registerOption(SVNOption.FILE); SVNCommandLine.registerOption(SVNOption.ENCODING); SVNCommandLine.registerOption(SVNOption.TARGETS); SVNCommandLine.registerOption(SVNOption.FORCE); SVNCommandLine.registerOption(SVNOption.FORCE_LOG); SVNCommandLine.registerOption(SVNOption.MESSAGE); SVNCommandLine.registerOption(SVNOption.WITH_REVPROP); SVNCommandLine.registerOption(SVNOption.EDITOR_CMD); SVNCommandLine.registerOption(SVNOption.NO_UNLOCK); SVNCommandLine.registerOption(SVNOption.DRY_RUN); SVNCommandLine.registerOption(SVNOption.RECORD_ONLY); SVNCommandLine.registerOption(SVNOption.USE_MERGE_HISTORY); SVNCommandLine.registerOption(SVNOption.EXTENSIONS); SVNCommandLine.registerOption(SVNOption.IGNORE_ANCESTRY); SVNCommandLine.registerOption(SVNOption.SHOW_COPIES_AS_ADDS); SVNCommandLine.registerOption(SVNOption.NATIVE_EOL); SVNCommandLine.registerOption(SVNOption.RELOCATE); SVNCommandLine.registerOption(SVNOption.AUTOPROPS); SVNCommandLine.registerOption(SVNOption.NO_AUTOPROPS); SVNCommandLine.registerOption(SVNOption.KEEP_CHANGELISTS); SVNCommandLine.registerOption(SVNOption.PARENTS); SVNCommandLine.registerOption(SVNOption.KEEP_LOCAL); SVNCommandLine.registerOption(SVNOption.ACCEPT); SVNCommandLine.registerOption(SVNOption.REMOVE); SVNCommandLine.registerOption(SVNOption.DIFF); SVNCommandLine.registerOption(SVNOption.OLD); SVNCommandLine.registerOption(SVNOption.NEW); SVNCommandLine.registerOption(SVNOption.SUMMARIZE); SVNCommandLine.registerOption(SVNOption.NOTICE_ANCESTRY); SVNCommandLine.registerOption(SVNOption.NO_DIFF_DELETED); SVNCommandLine.registerOption(SVNOption.STOP_ON_COPY); SVNCommandLine.registerOption(SVNOption.LIMIT); SVNCommandLine.registerOption(SVNOption.AUTHOR_OF_INTEREST); SVNCommandLine.registerOption(SVNOption.REGULAR_EXPRESSION); SVNCommandLine.registerOption(SVNOption.GIT_DIFF_FORMAT); SVNCommandLine.registerOption(SVNOption.USERNAME); SVNCommandLine.registerOption(SVNOption.PASSWORD); SVNCommandLine.registerOption(SVNOption.NO_AUTH_CACHE); SVNCommandLine.registerOption(SVNOption.NON_INTERACTIVE); SVNCommandLine.registerOption(SVNOption.WITH_ALL_REVPROPS); SVNCommandLine.registerOption(SVNOption.SHOW_REVS); SVNCommandLine.registerOption(SVNOption.REINTEGRATE); SVNCommandLine.registerOption(SVNOption.ALLOW_MIXED_REVISIONS); SVNCommandLine.registerOption(SVNOption.DIFF_CMD); SVNCommandLine.registerOption(SVNOption.TRUST_SERVER_CERT); SVNCommandLine.registerOption(SVNOption.CONFIG_OPTION); SVNCommandLine.registerOption(SVNOption.STRIP); } protected boolean needArgs() { return true; } protected boolean needCommand() { return true; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNAddCommand.java000066400000000000000000000075631177510526000307200ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAddCommand extends SVNCommand { public SVNAddCommand() { super("add", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.TARGETS); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.QUIET); options.add(SVNOption.FORCE); options.add(SVNOption.NO_IGNORE); options.add(SVNOption.AUTOPROPS); options.add(SVNOption.NO_AUTOPROPS); options.add(SVNOption.PARENTS); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.INFINITY; } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } boolean hasMissingPaths = false; boolean hasPresentPaths = false; for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isURL()) { continue; } try { client.doAdd(target.getFile(), getSVNEnvironment().isForce(), false, getSVNEnvironment().isParents(), depth, getSVNEnvironment().isNoIgnore(), getSVNEnvironment().isParents()); } catch (SVNException e) { hasMissingPaths |= e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_PATH_NOT_FOUND; hasPresentPaths |= e.getErrorMessage().getErrorCode() == SVNErrorCode.ENTRY_EXISTS; getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.ENTRY_EXISTS, SVNErrorCode.WC_PATH_NOT_FOUND}, getSVNEnvironment().isQuiet()); } } if (hasMissingPaths) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not add all targets because some targets don't exist"); SVNErrorManager.error(err, SVNLogType.WC); } if (hasPresentPaths) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not add all targets because some targets are already versioned"); SVNErrorManager.error(err, SVNLogType.WC); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNBlameCommand.java000066400000000000000000000235051177510526000312420ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.ISVNAnnotateHandler; import org.tmatesoft.svn.core.wc.SVNLogClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNBlameCommand extends SVNXMLCommand implements ISVNAnnotateHandler { private StringBuffer myBuffer; public SVNBlameCommand() { super("blame", new String[] {"praise", "annotate", "ann"}); } public boolean acceptsRevisionRange() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.VERBOSE); options.add(SVNOption.USE_MERGE_HISTORY); options.add(SVNOption.INCREMENTAL); options.add(SVNOption.XML); options.add(SVNOption.EXTENSIONS); options.add(SVNOption.FORCE); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(null, true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNRevision start = getSVNEnvironment().getStartRevision(); SVNRevision end = getSVNEnvironment().getEndRevision(); if (end == SVNRevision.UNDEFINED) { if (start != SVNRevision.UNDEFINED) { end = start; start = SVNRevision.create(1); } } if (start == SVNRevision.UNDEFINED) { start = SVNRevision.create(1); } if (getSVNEnvironment().isXML()) { if (getSVNEnvironment().isVerbose()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'verbose' option invalid in XML mode"), SVNLogType.CLIENT); } if (!getSVNEnvironment().isIncremental()) { printXMLHeader("blame"); } } else if (getSVNEnvironment().isIncremental()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'incremental' option only valid in XML mode"), SVNLogType.CLIENT); } myBuffer = new StringBuffer(); SVNLogClient client = getSVNEnvironment().getClientManager().getLogClient(); client.setDiffOptions(getSVNEnvironment().getDiffOptions()); boolean hasMissingTargets = false; for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName, true); SVNRevision endRev = end; if (endRev == SVNRevision.UNDEFINED) { if (target.getPegRevision() != SVNRevision.UNDEFINED) { endRev = target.getPegRevision(); } } if (getSVNEnvironment().isXML()) { myBuffer = openXMLTag("target", SVNXMLUtil.XML_STYLE_NORMAL, "path", SVNCommandUtil.getLocalPath(target.getTarget()), myBuffer); } try { if (target.isFile()) { client.doAnnotate(target.getFile(), target.getPegRevision(), start, endRev, getSVNEnvironment().isForce(), getSVNEnvironment().isUseMergeHistory(), this, null); } else { client.doAnnotate(target.getURL(), target.getPegRevision(), start, endRev, getSVNEnvironment().isForce(), getSVNEnvironment().isUseMergeHistory(), this, null); } if (getSVNEnvironment().isXML()) { myBuffer = closeXMLTag("target", myBuffer); getSVNEnvironment().getOut().print(myBuffer); } } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.CLIENT_IS_BINARY_FILE) { getSVNEnvironment().getErr().println("Skipping binary file: '" + SVNCommandUtil.getLocalPath(targetName) + "'"); } else { getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.WC_PATH_NOT_FOUND, SVNErrorCode.FS_NOT_FILE, SVNErrorCode.FS_NOT_FOUND}, getSVNEnvironment().isQuiet()); hasMissingTargets = true; } } myBuffer = myBuffer.delete(0, myBuffer.length()); } if (getSVNEnvironment().isXML() && !getSVNEnvironment().isIncremental()) { printXMLFooter("blame"); } if (hasMissingTargets) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not perform blame on all targets because some " + "targets don't exist"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } private int myCurrentLineNumber = 0; public void handleLine(Date date, long revision, String author, String line) throws SVNException { myCurrentLineNumber++; handleLine(date, revision, author, line, null, -1, null, null, myCurrentLineNumber); } public void handleLine(Date date, long revision, String author, String line, Date mergedDate, long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException { if (getSVNEnvironment().isXML()) { myBuffer = openXMLTag("entry", SVNXMLUtil.XML_STYLE_NORMAL, "line-number", Long.toString(lineNumber + 1), myBuffer); if (SVNRevision.isValidRevisionNumber(revision)) { myBuffer = openXMLTag("commit", SVNXMLUtil.XML_STYLE_NORMAL, "revision", Long.toString(revision), myBuffer); myBuffer = openCDataTag("author", author, myBuffer); myBuffer = openCDataTag("date", ((SVNDate) date).format(), myBuffer); myBuffer = closeXMLTag("commit", myBuffer); } if (getSVNEnvironment().isUseMergeHistory() && SVNRevision.isValidRevisionNumber(mergedRevision)) { myBuffer = openXMLTag("merged", SVNXMLUtil.XML_STYLE_NORMAL, "path", mergedPath, myBuffer); myBuffer = openXMLTag("commit", SVNXMLUtil.XML_STYLE_NORMAL, "revision", Long.toString(mergedRevision), myBuffer); myBuffer = openCDataTag("author", mergedAuthor, myBuffer); myBuffer = openCDataTag("date", ((SVNDate) mergedDate).format(), myBuffer); myBuffer = closeXMLTag("commit", myBuffer); myBuffer = closeXMLTag("merged", myBuffer); } myBuffer = closeXMLTag("entry", myBuffer); } else { String mergedStr = ""; if (getSVNEnvironment().isUseMergeHistory()) { if (revision > mergedRevision) { mergedStr = "G "; date = mergedDate; revision = mergedRevision; author = mergedAuthor; } else { mergedStr = " "; } } String revStr = revision >= 0 ? SVNFormatUtil.formatString(Long.toString(revision), 6, false) : " -"; String authorStr = author != null ? SVNFormatUtil.formatString(author, 10, false) : " -"; if (getSVNEnvironment().isVerbose()) { String dateStr = " -"; if (date != null) { dateStr = SVNDate.formatHumanDate(date, getSVNEnvironment().getClientManager().getOptions()); } getSVNEnvironment().getOut().print(mergedStr + revStr + " " + authorStr + " " + dateStr + " "); if (getSVNEnvironment().isUseMergeHistory() && mergedPath != null) { String pathStr = SVNFormatUtil.formatString(mergedPath, 14, true); getSVNEnvironment().getOut().print(pathStr + " "); } getSVNEnvironment().getOut().println(line); } else { getSVNEnvironment().getOut().println(mergedStr + revStr + " " + authorStr + " " + line); } } } public boolean handleRevision(Date date, long revision, String author, File contents) throws SVNException { return false; } public void handleEOF() { } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNCatCommand.java000066400000000000000000000057011177510526000307270ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCatCommand extends SVNCommand { public SVNCatCommand() { super("cat", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(null, true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); boolean seenNonExistentTarget = false; for(int i = 0; i < targets.size(); i++) { SVNPath target = new SVNPath((String) targets.get(i), true); try { if (target.isURL()) { client.doGetFileContents(target.getURL(), target.getPegRevision(), getSVNEnvironment().getStartRevision(), true, getSVNEnvironment().getOut()); } else { client.doGetFileContents(target.getFile(), target.getPegRevision(), getSVNEnvironment().getStartRevision(), true, getSVNEnvironment().getOut()); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); getSVNEnvironment().handleWarning(err, new SVNErrorCode[] {SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.ENTRY_NOT_FOUND, SVNErrorCode.CLIENT_IS_DIRECTORY, SVNErrorCode.FS_NOT_FOUND}, getSVNEnvironment().isQuiet()); seenNonExistentTarget = true; } } if (seenNonExistentTarget) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not cat all targets because some targets don't exist"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNChangeListCommand.java000066400000000000000000000114411177510526000322370ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNChangelistClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNChangeListCommand extends SVNCommand { public SVNChangeListCommand() { super("changelist", new String[] {"cl"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.QUIET); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.REMOVE); options.add(SVNOption.TARGETS); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { List targets = new ArrayList(); String changelist = null; if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (getSVNEnvironment().isRemove()) { if (targets.size() < 1) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } changelist = null; } else { if (targets.size() < 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } changelist = (String) targets.remove(0); } Collection paths = new ArrayList(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); paths.add(target.getFile()); } File[] files = (File[]) paths.toArray(new File[paths.size()]); SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } SVNChangelistClient client = getSVNEnvironment().getClientManager().getChangelistClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } Collection errors = new ArrayList(); for (int i = 0; i < files.length; i++) { try { if (changelist != null) { client.doAddToChangelist(new File[] {files[i]}, depth, changelist, getSVNEnvironment().getChangelists()); } else { client.doRemoveFromChangelist(new File[] {files[i]}, depth, getSVNEnvironment().getChangelists()); } } catch (SVNException e) { if (!getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.WC_PATH_NOT_FOUND}, getSVNEnvironment().isQuiet())) { errors.add(e.getErrorMessage().getErrorCode()); } } } if (!errors.isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET); for (SVNErrorCode code : errors) { if (code == SVNErrorCode.WC_PATH_NOT_FOUND) { err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not set changelist on all targets because some" + " targets don't exist"); } else if (code == SVNErrorCode.UNVERSIONED_RESOURCE) { err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not set changelist on all targets because some" + " targets are not versioned"); } } SVNErrorManager.error(err, SVNLogType.CLIENT); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNCheckoutCommand.java000066400000000000000000000102401177510526000317570ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNUpdateClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCheckoutCommand extends SVNCommand { public SVNCheckoutCommand() { super("checkout", new String[] {"co"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.QUIET); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.FORCE); options.add(SVNOption.IGNORE_EXTERNALS); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(new ArrayList(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } String lastTarget = (String) targets.get(targets.size() - 1); if (SVNCommandUtil.isURL(lastTarget)) { if (targets.size() == 1) { SVNPath target = new SVNPath(lastTarget, true); lastTarget = target.getURL().getPath(); lastTarget = SVNPathUtil.tail(lastTarget); } else { lastTarget = ""; } targets.add(lastTarget); } else if (targets.size() == 1){ SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNUpdateClient client = getSVNEnvironment().getClientManager().getUpdateClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment(), true, false, false)); } SVNRevision revision = getSVNEnvironment().getStartRevision(); for (int i = 0; i < targets.size() - 1; i++) { String targetName = (String) targets.get(i); SVNPath target = new SVNPath(targetName, true); if (!target.isURL()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.BAD_URL, "''{0}'' doesn not appear to be a URL", targetName), SVNLogType.CLIENT); } String targetDir; SVNPath dstTarget; if (targets.size() == 2) { // url + path targetDir = lastTarget; dstTarget = new SVNPath(targetDir); } else { // all urls + base dst. targetDir = target.getURL().getPath(); targetDir = SVNPathUtil.tail(targetDir); targetDir = SVNPathUtil.append(lastTarget, targetDir); dstTarget = new SVNPath(targetDir); } SVNRevision pegRevision = target.getPegRevision(); if (revision == SVNRevision.UNDEFINED) { revision = pegRevision != SVNRevision.UNDEFINED ? pegRevision : SVNRevision.HEAD; } client.doCheckout(target.getURL(), dstTarget.getFile(), pegRevision, revision, getSVNEnvironment().getDepth(), getSVNEnvironment().isForce()); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNCleanupCommand.java000066400000000000000000000033361177510526000316110ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNWCClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCleanupCommand extends SVNCommand { public SVNCleanupCommand() { super("cleanup", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.DIFF3_CMD); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { targets.add(""); } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { client.doCleanup(target.getFile()); } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNCommand.java000066400000000000000000000042451177510526000303010ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.cli.AbstractSVNCommand; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class SVNCommand extends AbstractSVNCommand { private Collection myGlobalOptions; protected SVNCommand(String name, String[] aliases) { super(name, aliases); } public boolean acceptsRevisionRange() { return false; } public boolean isCommitter() { return false; } public String getFileAmbigousErrorMessage() { return "Log message file is a versioned file; use '--force-log' to override"; } public String getMessageAmbigousErrorMessage() { return "The log message is a path name (was -F intended?); use '--force-log' to override"; } protected SVNCommandEnvironment getSVNEnvironment() { return (SVNCommandEnvironment) getEnvironment(); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svn.commands"; } public Collection getGlobalOptions() { if (myGlobalOptions == null) { myGlobalOptions = new LinkedList(); myGlobalOptions.add(SVNOption.USERNAME); myGlobalOptions.add(SVNOption.PASSWORD); myGlobalOptions.add(SVNOption.NO_AUTH_CACHE); myGlobalOptions.add(SVNOption.NON_INTERACTIVE); myGlobalOptions.add(SVNOption.TRUST_SERVER_CERT); myGlobalOptions.add(SVNOption.CONFIG_DIR); myGlobalOptions.add(SVNOption.CONFIG_OPTION); } return myGlobalOptions; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNCommandEnvironment.java000066400000000000000000001330171177510526000325260ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNOption; import org.tmatesoft.svn.cli.SVNCommandLine; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.cli.SVNConsoleAuthenticationProvider; import org.tmatesoft.svn.cli.SVNOptionValue; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.util.SVNHashSet; import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.ISVNAuthStoreHandler; import org.tmatesoft.svn.core.internal.wc.ISVNAuthenticationStorageOptions; import org.tmatesoft.svn.core.internal.wc.ISVNGnomeKeyringPasswordProvider; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.internal.wc.admin.SVNTranslator; import org.tmatesoft.svn.core.wc.ISVNCommitHandler; import org.tmatesoft.svn.core.wc.SVNCommitItem; import org.tmatesoft.svn.core.wc.SVNDiffOptions; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNRevisionRange; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCommandEnvironment extends AbstractSVNCommandEnvironment implements ISVNCommitHandler { private static final String DEFAULT_LOG_MESSAGE_HEADER = "--This line, and those below, will be ignored--"; private SVNDepth myDepth; private SVNDepth mySetDepth; private boolean myIsVerbose; private boolean myIsUpdate; private boolean myIsQuiet; private boolean myIsIncremental; private boolean myIsHelp; private boolean myIsIgnoreExternals; private boolean myIsIgnoreKeywords; private boolean myIsXML; private boolean myIsVersion; private String myChangelist; private boolean myIsNonInteractive; private boolean myIsNoAuthCache; private String myUserName; private String myPassword; private String myConfigDir; private boolean myIsDescend; private boolean myIsNoIgnore; private boolean myIsRevprop; private boolean myIsStrict; private SVNRevision myStartRevision; private SVNRevision myEndRevision; private boolean myIsForce; private String myFilePath; private byte[] myFileData; private List myTargets; private String myEncoding; private String myMessage; private boolean myIsForceLog; private String myEditorCommand; private String myDiffCommand; private SVNProperties myRevisionProperties; private boolean myIsNoUnlock; private boolean myIsDryRun; private boolean myIsRecordOnly; private boolean myIsUseMergeHistory; private Collection myExtensions; private boolean myIsIgnoreAncestry; private boolean myIsShowCopiesAsAdds; private String myNativeEOL; private boolean myIsRelocate; private boolean myIsNoAutoProps; private boolean myIsAutoProps; private boolean myIsKeepChangelist; private boolean myIsParents; private boolean myIsKeepLocal; private SVNConflictAcceptPolicy myResolveAccept; private boolean myIsRemove; private String myNewTarget; private String myOldTarget; private boolean myIsNoticeAncestry; private boolean myIsSummarize; private boolean myIsNoDiffDeleted; private long myLimit; private boolean myIsStopOnCopy; private boolean myIsChangeOptionUsed; private boolean myIsRevisionOptionUsed; private boolean myIsWithAllRevprops; private boolean myIsReIntegrate; private boolean myIsTrustServerCertificate; private boolean myIsAllowMixedRevisions; private List myRevisionRanges; private SVNShowRevisionType myShowRevsType; private Collection myChangelists; private String myAuthorOfInterest; private String myRegularExpression; private Map myConfigOptions; private Map myServersOptions; private boolean myIsGitDiffFormat; private boolean myIsShowDiff; private int myStripCount; public SVNCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { super(programName, out, err, in); myIsDescend = true; myLimit = -1; myResolveAccept = SVNConflictAcceptPolicy.UNSPECIFIED; myDepth = SVNDepth.UNKNOWN; mySetDepth = SVNDepth.UNKNOWN; myStartRevision = SVNRevision.UNDEFINED; myEndRevision = SVNRevision.UNDEFINED; myShowRevsType = SVNShowRevisionType.MERGED; myRevisionRanges = new LinkedList(); myChangelists = new SVNHashSet(); } public void initClientManager() throws SVNException { super.initClientManager(); getClientManager().setIgnoreExternals(myIsIgnoreExternals); } protected String refineCommandName(String commandName, SVNCommandLine commandLine) throws SVNException { for (Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); AbstractSVNOption option = optionValue.getOption(); if (option == SVNOption.HELP || option == SVNOption.QUESTION) { myIsHelp = true; } else if (option == SVNOption.VERSION) { myIsVersion = true; } } if (myIsHelp) { List newArguments = commandName != null ? Collections.singletonList(commandName) : Collections.EMPTY_LIST; setArguments(newArguments); return "help"; } if (commandName == null) { if (isVersion()) { SVNCommand versionCommand = new SVNCommand("--version", null) { protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNOption.VERSION); options.add(SVNOption.CONFIG_DIR); options.add(SVNOption.QUIET); return options; } public void run() throws SVNException { AbstractSVNCommand helpCommand = AbstractSVNCommand.getCommand("help"); helpCommand.init(SVNCommandEnvironment.this); helpCommand.run(); } }; AbstractSVNCommand.registerCommand(versionCommand); return "--version"; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Subcommand argument required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return commandName; } protected DefaultSVNOptions createClientOptions() throws SVNException { File configDir = myConfigDir != null ? new File(myConfigDir) : SVNWCUtil.getDefaultConfigurationDirectory(); DefaultSVNOptions options = SVNWCUtil.createDefaultOptions(configDir, true); options.setAuthStorageEnabled(!myIsNoAuthCache); if (myIsAutoProps) { options.setUseAutoProperties(true); } if (myIsNoAutoProps) { options.setUseAutoProperties(false); } if (myIsNoUnlock) { options.setKeepLocks(true); } if ((myResolveAccept == SVNConflictAcceptPolicy.UNSPECIFIED && (!options.isInteractiveConflictResolution() || myIsNonInteractive)) || myResolveAccept == SVNConflictAcceptPolicy.POSTPONE) { options.setConflictHandler(null); } else { if (myIsNonInteractive) { if (myResolveAccept == SVNConflictAcceptPolicy.EDIT) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "--accept={0} incompatible with --non-interactive", SVNConflictAcceptPolicy.EDIT); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (myResolveAccept == SVNConflictAcceptPolicy.LAUNCH) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "--accept={0} incompatible with --non-interactive", SVNConflictAcceptPolicy.LAUNCH); SVNErrorManager.error(err, SVNLogType.CLIENT); } } options.setConflictHandler(new SVNCommandLineConflictHandler(myResolveAccept, this)); } options.setInMemoryConfigOptions(myConfigOptions); return options; } protected ISVNAuthenticationManager createClientAuthenticationManager() { File configDir = myConfigDir != null ? new File(myConfigDir) : SVNWCUtil.getDefaultConfigurationDirectory(); final DefaultSVNAuthenticationManager authManager = (DefaultSVNAuthenticationManager) SVNWCUtil.createDefaultAuthenticationManager(configDir, myUserName, myPassword, !myIsNoAuthCache); final ISVNAuthStoreHandler authStoreHandler; final ISVNGnomeKeyringPasswordProvider gnomeKeyringPasswordProvider; if (!myIsNonInteractive) { SVNConsoleAuthenticationProvider consoleAuthProvider = new SVNConsoleAuthenticationProvider(myIsTrustServerCertificate); authManager.setAuthenticationProvider(consoleAuthProvider); authStoreHandler = consoleAuthProvider; gnomeKeyringPasswordProvider = consoleAuthProvider; } else { authStoreHandler = null; gnomeKeyringPasswordProvider = null; } ISVNAuthenticationStorageOptions authOpts = new ISVNAuthenticationStorageOptions() { public boolean isNonInteractive() throws SVNException { return myIsNonInteractive; } public ISVNAuthStoreHandler getAuthStoreHandler() throws SVNException { return authStoreHandler; } public boolean isSSLPassphrasePromptSupported() { return authManager.isSSLPassphrasePromtSupported(); } public ISVNGnomeKeyringPasswordProvider getGnomeKeyringPasswordProvider() { return gnomeKeyringPasswordProvider; } }; authManager.setAuthenticationStorageOptions(authOpts); authManager.setInMemoryConfigOptions(myConfigOptions); authManager.setInMemoryServersOptions(myServersOptions); return authManager; } protected void initOptions(SVNCommandLine commandLine) throws SVNException { super.initOptions(commandLine); if (getCommand().getClass() != SVNMergeCommand.class && getCommand().getClass() != SVNLogCommand.class) { if (myRevisionRanges.size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Multiple revision argument encountered; " + "can't specify -c twice, or both -c and -r"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else if (!myRevisionRanges.isEmpty() && myIsReIntegrate) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "-r and -c can't be used with --reintegrate"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (myRevisionRanges.isEmpty()) { SVNRevisionRange range = new SVNRevisionRange(SVNRevision.UNDEFINED, SVNRevision.UNDEFINED); myRevisionRanges.add(range); } SVNRevisionRange range = (SVNRevisionRange) myRevisionRanges.get(0); myStartRevision = range.getStartRevision(); myEndRevision = range.getEndRevision(); if (myIsReIntegrate) { if (myIsIgnoreAncestry) { if (myIsRecordOnly) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--reintegrate cannot be used with --ignore-ancestry or --record-only"); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--reintegrate cannot be used with --ignore-ancestry"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else if (myIsRecordOnly) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--reintegrate cannot be used with --record-only"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } if (myIsTrustServerCertificate && !myIsNonInteractive) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "--trust-server-cert requires --non-interactive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNOption.LIMIT) { String limitStr = optionValue.getValue(); try { long limit = Long.parseLong(limitStr); if (limit <= 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCORRECT_PARAMS, "Argument to --limit must be positive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } myLimit = limit; } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric limit argument given"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else if (option == SVNOption.MESSAGE) { myMessage = optionValue.getValue(); } else if (option == SVNOption.CHANGE) { if (myOldTarget != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old"); SVNErrorManager.error(err, SVNLogType.CLIENT); } String chValue = optionValue.getValue(); for(StringTokenizer tokens = new StringTokenizer(chValue, ", \n\r\t"); tokens.hasMoreTokens();) { String token = tokens.nextToken(); boolean isNegative = false; if (token.startsWith("-")) { token = token.substring(1); isNegative = true; } while (token.startsWith("r")) { token = token.substring(1); } long change = 0; long changeEnd = 0; try { if (token.indexOf("-") > 0) { if (isNegative || token.startsWith("-")) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Negative number in range ({0}) is not supported with -c", token); SVNErrorManager.error(err, SVNLogType.CLIENT); } String firstPart = token.substring(0, token.indexOf("-")); String secondPart = token.substring(token.indexOf("-") + 1); change = Long.parseLong(firstPart); while (secondPart.startsWith("r")) { secondPart = secondPart.substring(1); } changeEnd = Long.parseLong(secondPart); } else { change = Long.parseLong(token); changeEnd = change; } } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric change argument ({0}) given to -c", token); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (isNegative) { change = -change; } SVNRevisionRange range = null; if (change == 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "There is no change 0"); SVNErrorManager.error(err, SVNLogType.CLIENT); } else if (change > 0) { if (change <= changeEnd) { change--; } else { changeEnd--; } range = new SVNRevisionRange(SVNRevision.create(change), SVNRevision.create(changeEnd)); } else { change = -change; changeEnd = change - 1; range = new SVNRevisionRange(SVNRevision.create(change), SVNRevision.create(changeEnd)); } myIsChangeOptionUsed = true; myRevisionRanges.add(range); } } else if (option == SVNOption.REVISION) { String revStr = optionValue.getValue(); SVNRevision[] revisions = parseRevision(revStr); if (revisions == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Syntax error in revision argument ''{0}''", revStr); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNRevisionRange range = new SVNRevisionRange(revisions[0], revisions[1]); myRevisionRanges.add(range); myIsRevisionOptionUsed = true; } else if (option == SVNOption.VERBOSE) { myIsVerbose = true; } else if (option == SVNOption.UPDATE) { myIsUpdate = true; } else if (option == SVNOption.HELP || option == SVNOption.QUESTION) { myIsHelp = true; } else if (option == SVNOption.QUIET) { myIsQuiet = true; } else if (option == SVNOption.INCREMENTAL) { myIsIncremental = true; } else if (option == SVNOption.FILE) { String fileName = optionValue.getValue(); myFilePath = fileName; myFileData = readFromFile(new File(fileName)); } else if (option == SVNOption.TARGETS) { String fileName = optionValue.getValue(); byte[] data = readFromFile(new File(fileName)); try { String[] targets = new String(data, "UTF-8").split("[\n\r]"); myTargets = new LinkedList(); for (int i = 0; i < targets.length; i++) { if (targets[i].trim().length() > 0) { myTargets.add(targets[i].trim()); } } } catch (UnsupportedEncodingException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else if (option == SVNOption.FORCE) { myIsForce = true; } else if (option == SVNOption.FORCE_LOG) { myIsForceLog = true; } else if (option == SVNOption.DRY_RUN) { myIsDryRun = true; } else if (option == SVNOption.REVPROP) { myIsRevprop = true; } else if (option == SVNOption.RECURSIVE) { myDepth = SVNDepth.fromRecurse(true); } else if (option == SVNOption.NON_RECURSIVE) { myIsDescend = false; } else if (option == SVNOption.DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { myDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { myDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { myDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { myDepth = SVNDepth.INFINITY; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''empty'', ''files'', ''immediates'', or ''infinity''", depth); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else if (option == SVNOption.SET_DEPTH) { String depth = optionValue.getValue(); if (SVNDepth.EMPTY.getName().equals(depth)) { mySetDepth = SVNDepth.EMPTY; } else if (SVNDepth.FILES.getName().equals(depth)) { mySetDepth = SVNDepth.FILES; } else if (SVNDepth.IMMEDIATES.getName().equals(depth)) { mySetDepth = SVNDepth.IMMEDIATES; } else if (SVNDepth.INFINITY.getName().equals(depth)) { mySetDepth = SVNDepth.INFINITY; } else if (SVNDepth.EXCLUDE.getName().equals(depth)) { mySetDepth = SVNDepth.EXCLUDE; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid depth; try ''exclude'', ''empty'', ''files'', ''immediates'', or ''infinity''", depth); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else if (option == SVNOption.VERSION) { myIsVersion = true; } else if (option == SVNOption.USERNAME) { myUserName = optionValue.getValue(); } else if (option == SVNOption.PASSWORD) { myPassword = optionValue.getValue(); } else if (option == SVNOption.ENCODING) { myEncoding = optionValue.getValue(); } else if (option == SVNOption.XML) { myIsXML = true; } else if (option == SVNOption.STOP_ON_COPY) { myIsStopOnCopy = true; } else if (option == SVNOption.STRICT) { myIsStrict = true; } else if (option == SVNOption.NO_AUTH_CACHE) { myIsNoAuthCache = true; } else if (option == SVNOption.NON_INTERACTIVE) { myIsNonInteractive = true; } else if (option == SVNOption.NO_DIFF_DELETED) { myIsNoDiffDeleted = true; } else if (option == SVNOption.NOTICE_ANCESTRY) { myIsNoticeAncestry = true; } else if (option == SVNOption.IGNORE_ANCESTRY) { myIsIgnoreAncestry = true; } else if (option == SVNOption.SHOW_COPIES_AS_ADDS) { myIsShowCopiesAsAdds = true; } else if (option == SVNOption.GIT_DIFF_FORMAT) { myIsGitDiffFormat = true; } else if (option == SVNOption.DIFF) { myIsShowDiff = true; } else if (option == SVNOption.IGNORE_EXTERNALS) { myIsIgnoreExternals = true; } else if (option == SVNOption.IGNORE_KEYWORDS) { myIsIgnoreKeywords = true; } else if (option == SVNOption.RELOCATE) { if (myDepth != SVNDepth.UNKNOWN) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--depth and --relocate are mutually exclusive"), SVNLogType.CLIENT); } myIsRelocate = true; } else if (option == SVNOption.EXTENSIONS) { String extensionsString = optionValue.getValue(); String[] extensions = extensionsString.trim().split("\\s+"); if (myExtensions == null) { myExtensions = new SVNHashSet(); } myExtensions.addAll(Arrays.asList(extensions)); } else if (option == SVNOption.RECORD_ONLY) { myIsRecordOnly = true; } else if (option == SVNOption.DIFF_CMD) { myDiffCommand = optionValue.getValue(); } else if (option == SVNOption.EDITOR_CMD) { myEditorCommand = optionValue.getValue(); } else if (option == SVNOption.OLD) { if (myIsChangeOptionUsed) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Can't specify -c with --old"), SVNLogType.CLIENT); } myOldTarget = optionValue.getValue(); } else if (option == SVNOption.NEW) { myNewTarget = optionValue.getValue(); } else if (option == SVNOption.CONFIG_DIR) { myConfigDir = optionValue.getValue(); } else if (option == SVNOption.CONFIG_OPTION) { if (myConfigOptions == null) { myConfigOptions = new HashMap(); } if (myServersOptions == null) { myServersOptions = new HashMap(); } SVNCommandUtil.parseConfigOption(optionValue.getValue(), myConfigOptions, myServersOptions); } else if (option == SVNOption.AUTOPROPS) { if (myIsNoAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive"), SVNLogType.CLIENT); } myIsAutoProps = true; } else if (option == SVNOption.NO_AUTOPROPS) { if (myIsAutoProps) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--auto-props and --no-auto-props are mutually exclusive"), SVNLogType.CLIENT); } myIsNoAutoProps = true; } else if (option == SVNOption.NATIVE_EOL) { myNativeEOL = optionValue.getValue(); } else if (option == SVNOption.NO_UNLOCK) { myIsNoUnlock = true; } else if (option == SVNOption.SUMMARIZE) { myIsSummarize = true; } else if (option == SVNOption.REMOVE) { myIsRemove = true; } else if (option == SVNOption.CHANGELIST) { myChangelist = optionValue.getValue(); if (myChangelist == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Changelist names must not be empty"); SVNErrorManager.error(err, SVNLogType.CLIENT); } myChangelists.add(myChangelist); } else if (option == SVNOption.KEEP_CHANGELISTS) { myIsKeepChangelist = true; } else if (option == SVNOption.KEEP_LOCAL) { myIsKeepLocal = true; } else if (option == SVNOption.NO_IGNORE) { myIsNoIgnore = true; } else if (option == SVNOption.WITH_ALL_REVPROPS) { myIsWithAllRevprops = true; } else if (option == SVNOption.WITH_REVPROP) { parseRevisionProperty(optionValue); } else if (option == SVNOption.PARENTS) { myIsParents = true; } else if (option == SVNOption.USE_MERGE_HISTORY) { myIsUseMergeHistory = true; } else if (option == SVNOption.ACCEPT) { SVNConflictAcceptPolicy accept = SVNConflictAcceptPolicy.fromString(optionValue.getValue()); if (accept == SVNConflictAcceptPolicy.INVALID) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid --accept value;", optionValue.getValue()); SVNErrorManager.error(err, SVNLogType.CLIENT); } myResolveAccept = accept; } else if (option == SVNOption.SHOW_REVS) { myShowRevsType = SVNShowRevisionType.fromString(optionValue.getValue()); if (myShowRevsType == SVNShowRevisionType.INVALID) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid --show-revs value", optionValue.getValue()); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else if (option == SVNOption.REINTEGRATE) { myIsReIntegrate = true; } else if (option == SVNOption.ALLOW_MIXED_REVISIONS) { myIsAllowMixedRevisions = true; } else if (option == SVNOption.AUTHOR_OF_INTEREST) { myAuthorOfInterest = optionValue.getValue(); } else if (option == SVNOption.REGULAR_EXPRESSION) { myRegularExpression = optionValue.getValue(); } else if (option == SVNOption.TRUST_SERVER_CERT) { myIsTrustServerCertificate = true; } else if(option == SVNOption.STRIP ) { final String value = optionValue.getValue(); try { myStripCount = Integer.parseInt(optionValue.getValue()); } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric change argument ({0}) given to -strip", value); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } protected SVNCommand getSVNCommand() { return (SVNCommand) getCommand(); } protected void validateOptions(SVNCommandLine commandLine) throws SVNException { super.validateOptions(commandLine); if (!isForceLog() && getSVNCommand().isCommitter()) { if (myFilePath != null) { if (isVersioned(myFilePath)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_LOG_MESSAGE_IS_VERSIONED_FILE, getSVNCommand().getFileAmbigousErrorMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } } if (myMessage != null && !"".equals(myMessage)) { File file = new File(myMessage).getAbsoluteFile(); if (SVNFileType.getType(file) != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_LOG_MESSAGE_IS_PATHNAME, getSVNCommand().getMessageAmbigousErrorMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } if (!getSVNCommand().acceptsRevisionRange() && getEndRevision() != SVNRevision.UNDEFINED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_REVISION_RANGE); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (!myIsDescend) { if (getCommand() instanceof SVNStatusCommand) { myDepth = SVNDepth.IMMEDIATES; } else if (getCommand() instanceof SVNRevertCommand || getCommand() instanceof SVNAddCommand || getCommand() instanceof SVNCommitCommand) { myDepth = SVNDepth.EMPTY; } else { myDepth = SVNDepth.FILES; } } if ("relocate".equals(getCommandName())) { myIsRelocate = true; } } protected String getCommandLineClientName() { return "svn"; } public boolean isReIntegrate() { return myIsReIntegrate; } public SVNShowRevisionType getShowRevisionType() { return myShowRevsType; } public boolean isChangeOptionUsed() { return myIsChangeOptionUsed; } public boolean isRevisionOptionUsed() { return myIsRevisionOptionUsed; } public String getChangelist() { return myChangelist; } public String[] getChangelists() { if (myChangelists != null && !myChangelists.isEmpty()) { return (String[]) myChangelists.toArray(new String[myChangelists.size()]); } return null; } public Collection getChangelistsCollection() { return myChangelists; } public boolean isIgnoreKeywords() { return myIsIgnoreKeywords; } public SVNDepth getDepth() { return myDepth; } public SVNDepth getSetDepth() { return mySetDepth; } public boolean isVerbose() { return myIsVerbose; } public boolean isNoIgnore() { return myIsNoIgnore; } public boolean isUpdate() { return myIsUpdate; } public boolean isQuiet() { return myIsQuiet; } public boolean isIncremental() { return myIsIncremental; } public boolean isRevprop() { return myIsRevprop; } public boolean isStrict() { return myIsStrict; } public List getRevisionRanges() { return myRevisionRanges; } public SVNRevision getStartRevision() { return myStartRevision; } public SVNRevision getEndRevision() { return myEndRevision; } public boolean isXML() { return myIsXML; } public boolean isVersion() { return myIsVersion; } public boolean isForce() { return myIsForce; } public String getEncoding() { return myEncoding; } public byte[] getFileData() { return myFileData; } public List getTargets() { return myTargets; } public boolean isForceLog() { return myIsForceLog; } public String getEditorCommand() { return myEditorCommand; } public String getDiffCommand() { return myDiffCommand; } public String getMessage() { return myMessage; } public SVNProperties getRevisionProperties() { return myRevisionProperties; } public boolean isDryRun() { return myIsDryRun; } public boolean isIgnoreAncestry() { return myIsIgnoreAncestry; } public boolean isShowCopiesAsAdds() { return myIsShowCopiesAsAdds; } public boolean isGitDiffFormat() { return myIsGitDiffFormat; } public boolean isShowDiff() { return myIsShowDiff; } public boolean isUseMergeHistory() { return myIsUseMergeHistory; } public boolean isRecordOnly() { return myIsRecordOnly; } public Collection getExtensions() { return myExtensions; } public String getNativeEOL() { return myNativeEOL; } public boolean isRelocate() { return myIsRelocate; } public boolean isNoUnlock() { return myIsNoUnlock; } public boolean isKeepChangelist() { return myIsKeepChangelist; } public boolean isParents() { return myIsParents; } public boolean isKeepLocal() { return myIsKeepLocal; } public SVNConflictAcceptPolicy getResolveAccept() { return myResolveAccept; } public boolean isRemove() { return myIsRemove; } public boolean isSummarize() { return myIsSummarize; } public boolean isNoticeAncestry() { return myIsNoticeAncestry; } public boolean isNoDiffDeleted() { return myIsNoDiffDeleted; } public String getOldTarget() { return myOldTarget; } public String getNewTarget() { return myNewTarget; } public String getAuthorOfInterest() { return myAuthorOfInterest; } public String getRegularExpression() { return myRegularExpression; } public long getLimit() { return myLimit; } public boolean isStopOnCopy() { return myIsStopOnCopy; } public boolean isAllRevisionProperties() { return myIsWithAllRevprops; } public int getStripCount() { return myStripCount; } public SVNDiffOptions getDiffOptions() throws SVNException { if (myExtensions == null) { return null; } LinkedList extensions = new LinkedList(myExtensions); boolean ignoreAllWS = myExtensions.contains("-w") || myExtensions.contains("--ignore-all-space"); if (ignoreAllWS) { extensions.remove("-w"); extensions.remove("--ignore-all-space"); } boolean ignoreAmountOfWS = myExtensions.contains("-b") || myExtensions.contains("--ignore-space-change"); if (ignoreAmountOfWS) { extensions.remove("-b"); extensions.remove("--ignore-space-change"); } boolean ignoreEOLStyle = myExtensions.contains("--ignore-eol-style"); if (ignoreEOLStyle) { extensions.remove("--ignore-eol-style"); } if (!extensions.isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INVALID_DIFF_OPTION, "Invalid argument ''{0}'' in diff options", extensions.get(0)); SVNErrorManager.error(err, SVNLogType.CLIENT); } return new SVNDiffOptions(ignoreAllWS, ignoreAmountOfWS, ignoreEOLStyle); } public boolean isAllowMixedRevisions() { return myIsAllowMixedRevisions; } public SVNProperties getRevisionProperties(String message, SVNCommitItem[] commitables, SVNProperties revisionProperties) throws SVNException { return revisionProperties == null ? new SVNProperties() : revisionProperties; } public String getCommitMessage(String message, SVNCommitItem[] commitables) throws SVNException { if (getFileData() != null) { byte[] data = getFileData(); for (int i = 0; i < data.length; i++) { if (data[i] == 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_BAD_LOG_MESSAGE, "Log message contains a zero byte"), SVNLogType.CLIENT); } } String charset = getEncoding(); if (charset == null) { charset = getOptions().getLogEncoding(); } if (charset == null) { charset = getOptions().getNativeCharset(); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream os = SVNTranslator.getTranslatingOutputStream(bos, charset, new byte[] {'\n'}, false, null, false); try { os.write(getFileData()); os.close(); os = null; return new String(bos.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()), SVNLogType.CLIENT); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Error normalizing log message to internal format"), SVNLogType.CLIENT); } finally { SVNFileUtil.closeFile(os); } } else if (getMessage() != null) { return getMessage(); } if (commitables == null || commitables.length == 0) { return ""; } // invoke editor (if non-interactive). if (myIsNonInteractive) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Cannot invoke editor to get log message when non-interactive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } message = null; while(message == null) { message = createCommitMessageTemplate(commitables); byte[] messageData = null; try { try { messageData = message.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { messageData = message.getBytes(); } messageData = SVNCommandUtil.runEditor(this, getEditorCommand(), messageData, "svn-commit"); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.CL_NO_EXTERNAL_EDITOR) { SVNErrorMessage err = e.getErrorMessage().wrap( "Could not use external editor to fetch log message; " + "consider setting the $SVN_EDITOR environment variable " + "or using the --message (-m) or --file (-F) options"); SVNErrorManager.error(err, SVNLogType.CLIENT); } throw e; } if (messageData != null) { String editedMessage = null; try { editedMessage = getEncoding() != null ? new String(messageData, getEncoding()) : new String(messageData); } catch (UnsupportedEncodingException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (editedMessage.indexOf(DEFAULT_LOG_MESSAGE_HEADER) >= 0) { editedMessage = editedMessage.substring(0, editedMessage.indexOf(DEFAULT_LOG_MESSAGE_HEADER)); } if (!"a".equals(editedMessage.trim())) { return editedMessage; } } message = null; getOut().println("\nLog message unchanged or not specified\n" + "a)bort, c)ontinue, e)dit"); try { char c = (char) getIn().read(); if (c == 'a') { SVNErrorManager.cancel("", SVNLogType.CLIENT); } else if (c == 'c') { return ""; } else if (c == 'e') { continue; } } catch (IOException e) { } } SVNErrorManager.cancel("", SVNLogType.CLIENT); return null; } private void parseRevisionProperty(SVNOptionValue optionValue) throws SVNException { if (myRevisionProperties == null) { myRevisionProperties = new SVNProperties(); } String revProp = optionValue.getValue(); if (revProp == null || "".equals(revProp)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Revision property pair is empty"); SVNErrorManager.error(err, SVNLogType.CLIENT); } int index = revProp.indexOf('='); String revPropName = null; String revPropValue = null; if (index >= 0) { revPropName = revProp.substring(0, index); revPropValue = revProp.substring(index + 1); } else { revPropName = revProp; revPropValue = ""; } if (!SVNPropertiesManager.isValidPropertyName(revPropName)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME, "''{0}'' is not a valid Subversion property name", revPropName); SVNErrorManager.error(err, SVNLogType.CLIENT); } myRevisionProperties.put(revPropName, revPropValue); } private String createCommitMessageTemplate(SVNCommitItem[] items) { StringBuffer buffer = new StringBuffer(); buffer.append(System.getProperty("line.separator")); buffer.append(DEFAULT_LOG_MESSAGE_HEADER); buffer.append(System.getProperty("line.separator")); buffer.append(System.getProperty("line.separator")); for (int i = 0; i < items.length; i++) { SVNCommitItem item = items[i]; String path = item.getPath() != null ? item.getPath() : item.getURL().toString(); if ("".equals(path) || path == null) { path = "."; } if (item.isDeleted() && item.isAdded()) { buffer.append('R'); } else if (item.isDeleted()) { buffer.append('D'); } else if (item.isAdded()) { buffer.append('A'); } else if (item.isContentsModified()) { buffer.append('M'); } else { buffer.append('_'); } if (item.isPropertiesModified()) { buffer.append('M'); } else { buffer.append(' '); } if (!myIsNoUnlock && item.isLocked()) { buffer.append('L'); } else { buffer.append(' '); } if (item.isCopied()) { buffer.append("+ "); } else { buffer.append(" "); } buffer.append(path); buffer.append(System.getProperty("line.separator")); } return buffer.toString(); } } SVNCommandLineConflictHandler.java000066400000000000000000000575721177510526000340250ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.text.MessageFormat; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.internal.wc.FSMergerBySequence; import org.tmatesoft.svn.core.internal.wc.SVNDiffConflictChoiceStyle; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.wc.ISVNConflictHandler; import org.tmatesoft.svn.core.wc.SVNConflictAction; import org.tmatesoft.svn.core.wc.SVNConflictChoice; import org.tmatesoft.svn.core.wc.SVNConflictDescription; import org.tmatesoft.svn.core.wc.SVNConflictReason; import org.tmatesoft.svn.core.wc.SVNConflictResult; import org.tmatesoft.svn.core.wc.SVNDiffOptions; import org.tmatesoft.svn.core.wc.SVNMergeFileSet; import org.tmatesoft.svn.util.SVNLogType; import de.regnis.q.sequence.line.QSequenceLineRAData; import de.regnis.q.sequence.line.QSequenceLineRAFileData; /** * @version 1.3 * @author TMate Software Ltd. * @since 1.2.0 */ public class SVNCommandLineConflictHandler implements ISVNConflictHandler { private SVNConflictAcceptPolicy myAccept; private SVNCommandEnvironment mySVNEnvironment; private boolean myIsExternalFailed; public SVNCommandLineConflictHandler(SVNConflictAcceptPolicy accept, SVNCommandEnvironment environment) { myAccept = accept; mySVNEnvironment = environment; } public SVNConflictResult handleConflict(SVNConflictDescription conflictDescription) throws SVNException { if (conflictDescription.isTreeConflict()) { return null; } SVNMergeFileSet files = conflictDescription.getMergeFiles(); if (myAccept == SVNConflictAcceptPolicy.POSTPONE) { return new SVNConflictResult(SVNConflictChoice.POSTPONE, null); } else if (myAccept == SVNConflictAcceptPolicy.BASE) { return new SVNConflictResult(SVNConflictChoice.BASE, null); } else if (myAccept == SVNConflictAcceptPolicy.WORKING) { return new SVNConflictResult(SVNConflictChoice.MERGED, null); } else if (myAccept == SVNConflictAcceptPolicy.MINE_CONFLICT) { return new SVNConflictResult(SVNConflictChoice.MINE_CONFLICT, null); } else if (myAccept == SVNConflictAcceptPolicy.THEIRS_CONFLICT) { return new SVNConflictResult(SVNConflictChoice.THEIRS_CONFLICT, null); } else if (myAccept == SVNConflictAcceptPolicy.MINE_FULL) { return new SVNConflictResult(SVNConflictChoice.MINE_FULL, null); } else if (myAccept == SVNConflictAcceptPolicy.THEIRS_FULL) { return new SVNConflictResult(SVNConflictChoice.THEIRS_FULL, null); } else if (myAccept == SVNConflictAcceptPolicy.EDIT) { if (files.getResultFile() != null) { if (myIsExternalFailed) { return new SVNConflictResult(SVNConflictChoice.POSTPONE, null); } try { SVNCommandUtil.editFileExternally(mySVNEnvironment, mySVNEnvironment.getEditorCommand(), files.getResultFile().getAbsolutePath()); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.CL_NO_EXTERNAL_EDITOR) { mySVNEnvironment.getErr().println(svne.getErrorMessage().getMessage() != null ? svne.getErrorMessage().getMessage() : "No editor found, leaving all conflicts."); myIsExternalFailed = true; } else if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.EXTERNAL_PROGRAM) { String message = svne.getErrorMessage().getMessageTemplate() != null ? svne.getErrorMessage().getMessage() : "Error running editor, leaving all conflicts."; if (message.startsWith("svn: ")) { //hack: use the original message template without any prefixes (like 'svn:', 'svn:warning') //added to make update test 42 pass message = message.substring("svn: ".length()); } mySVNEnvironment.getErr().println(message); myIsExternalFailed = true; } else { throw svne; } } return new SVNConflictResult(SVNConflictChoice.MERGED, null); } } else if (myAccept == SVNConflictAcceptPolicy.LAUNCH) { if (files.getBaseFile() != null && files.getLocalFile() != null && files.getRepositoryFile() != null && files.getResultFile() != null) { if (myIsExternalFailed) { return new SVNConflictResult(SVNConflictChoice.POSTPONE, null); } boolean[] remainsInConflict = { false }; try { SVNCommandUtil.mergeFileExternally(mySVNEnvironment, files.getBaseFile().getAbsolutePath(), files.getRepositoryFile().getAbsolutePath(), files.getLocalFile().getAbsolutePath(), files.getResultFile().getAbsolutePath(), files.getWCPath(), remainsInConflict); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.CL_NO_EXTERNAL_MERGE_TOOL) { mySVNEnvironment.getErr().println(svne.getErrorMessage().getMessage() != null ? svne.getErrorMessage().getMessage() : "No merge tool found."); myIsExternalFailed = true; } else if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.EXTERNAL_PROGRAM) { mySVNEnvironment.getErr().println(svne.getErrorMessage().getMessage() != null ? svne.getErrorMessage().getMessage() : "Error running merge tool."); myIsExternalFailed = true; } throw svne; } if (remainsInConflict[0]) { return new SVNConflictResult(SVNConflictChoice.POSTPONE, null); } return new SVNConflictResult(SVNConflictChoice.MERGED, null); } } boolean saveMerged = false; SVNConflictChoice choice = SVNConflictChoice.POSTPONE; if ((conflictDescription.getNodeKind() == SVNNodeKind.FILE && conflictDescription.getConflictAction() == SVNConflictAction.EDIT && conflictDescription.getConflictReason() == SVNConflictReason.EDITED) || conflictDescription.isPropertyConflict()) { boolean performedEdit = false; boolean diffAllowed = false; boolean knowsSmth = false; String path = mySVNEnvironment.getRelativePath(files.getWCFile()); path = SVNCommandUtil.getLocalPath(path); if (conflictDescription.isPropertyConflict()) { String message = "Conflict for property ''{0}'' discovered on ''{1}''."; message = MessageFormat.format(message, new Object[] { conflictDescription.getPropertyName(), path }); mySVNEnvironment.getErr().println(message); if ((files.getLocalFile() == null && files.getRepositoryFile() != null) || (files.getLocalFile() != null && files.getRepositoryFile() == null)) { if (files.getLocalFile() != null) { String myVal = SVNFileUtil.readFile(files.getLocalFile()); message = MessageFormat.format("They want to delete the property, you want to change the value to ''{0}''.", new Object[] { myVal }); mySVNEnvironment.getErr().println(message); } else { String reposVal = SVNFileUtil.readFile(files.getRepositoryFile()); message = MessageFormat.format("They want to change the property value to ''{0}'', you want to delete the property.", new Object[] { reposVal }); mySVNEnvironment.getErr().println(message); } } } else { String message = "Conflict discovered in ''{0}''."; message = MessageFormat.format(message, new Object[] { path }); mySVNEnvironment.getErr().println(message); } if ((files.getResultFile() != null && files.getBaseFile() != null) || (files.getBaseFile() != null && files.getLocalFile() != null && files.getRepositoryFile() != null)) { diffAllowed = true; } while (true) { String message = "Select: (p) postpone"; if (diffAllowed) { message += ", (df) diff-full, (e) edit"; if (knowsSmth) { message += ", (r) resolved"; } if (!files.isBinary() && !conflictDescription.isPropertyConflict()) { message += ",\n (mc) mine-conflict, (tc) theirs-conflict"; } } else { if (knowsSmth) { message += ", (r) resolved"; } message += ",\n (mf) mine-full, (tf) theirs-full"; } message += ",\n (s) show all options: "; String answer = SVNCommandUtil.prompt(message, mySVNEnvironment); if ("s".equals(answer)) { mySVNEnvironment.getErr().println(); mySVNEnvironment.getErr().println(" (e) edit - change merged file in an editor"); mySVNEnvironment.getErr().println(" (df) diff-full - show all changes made to merged file"); mySVNEnvironment.getErr().println(" (r) resolved - accept merged version of file"); mySVNEnvironment.getErr().println(); mySVNEnvironment.getErr().println(" (dc) display-conflict - show all conflicts (ignoring merged version)"); mySVNEnvironment.getErr().println(" (mc) mine-conflict - accept my version for all conflicts (same)"); mySVNEnvironment.getErr().println(" (tc) theirs-conflict - accept their version for all conflicts (same)"); mySVNEnvironment.getErr().println(); mySVNEnvironment.getErr().println(" (mf) mine-full - accept my version of entire file (even non-conflicts)"); mySVNEnvironment.getErr().println(" (tf) theirs-full - accept their version of entire file (same)"); mySVNEnvironment.getErr().println(); mySVNEnvironment.getErr().println(" (p) postpone - mark the conflict to be resolved later"); mySVNEnvironment.getErr().println(" (l) launch - launch external tool to resolve conflict"); mySVNEnvironment.getErr().println(" (s) show all - show this list"); mySVNEnvironment.getErr().println(); } else if ("p".equals(answer)) { choice = SVNConflictChoice.POSTPONE; break; } else if ("mc".equals(answer)) { if (files.isBinary()) { mySVNEnvironment.getErr().println("Invalid option; cannot choose based on conflicts in a binary file."); mySVNEnvironment.getErr().println(); continue; } else if (conflictDescription.isPropertyConflict()) { mySVNEnvironment.getErr().println("Invalid option; cannot choose based on conflicts for properties."); mySVNEnvironment.getErr().println(); continue; } choice = SVNConflictChoice.MINE_CONFLICT; if (performedEdit) { saveMerged = true; } break; } else if ("tc".equals(answer)) { if (files.isBinary()) { mySVNEnvironment.getErr().println("Invalid option; cannot choose based on conflicts in a binary file."); mySVNEnvironment.getErr().println(); continue; } else if (conflictDescription.isPropertyConflict()) { mySVNEnvironment.getErr().println("Invalid option; cannot choose based on conflicts for properties."); mySVNEnvironment.getErr().println(); continue; } choice = SVNConflictChoice.THEIRS_CONFLICT; if (performedEdit) { saveMerged = true; } break; } else if ("mf".equals(answer)) { choice = SVNConflictChoice.MINE_FULL; if (performedEdit) { saveMerged = true; } break; } else if ("tf".equals(answer)) { choice = SVNConflictChoice.THEIRS_FULL; if (performedEdit) { saveMerged = true; } break; } else if ("dc".equals(answer)) { if (files.isBinary()) { mySVNEnvironment.getErr().println("Invalid option; cannot display conflicts for a binary file."); mySVNEnvironment.getErr().println(); continue; } else if (conflictDescription.isPropertyConflict()) { mySVNEnvironment.getErr().println("Invalid option; cannot display conflicts for properties."); mySVNEnvironment.getErr().println(); continue; } else if (files.getLocalFile() == null || files.getBaseFile() == null || files.getRepositoryFile() == null) { mySVNEnvironment.getErr().println("Invalid option; original files not available."); mySVNEnvironment.getErr().println(); continue; } //TODO: re-implement in future showConflictedChunks(files); knowsSmth = true; continue; } else if ("df".equals(answer)) { if (!diffAllowed) { mySVNEnvironment.getErr().println("Invalid option; there's no merged version to diff."); mySVNEnvironment.getErr().println(); continue; } File path1 = null; File path2 = null; if (files.getResultFile() != null && files.getBaseFile() != null) { path1 = files.getBaseFile(); path2 = files.getResultFile(); } else { path1 = files.getRepositoryFile(); path2 = files.getLocalFile(); } DefaultSVNCommandLineDiffGenerator diffGenerator = new DefaultSVNCommandLineDiffGenerator(path1, path2); diffGenerator.setDiffOptions(new SVNDiffOptions(false, false, true)); diffGenerator.displayFileDiff("", path1, path2, null, null, null, null, System.out); knowsSmth = true; } else if ("e".equals(answer)) { if (files.getResultFile() != null) { try { String resultPath = files.getResultFile().getAbsolutePath(); SVNCommandUtil.editFileExternally(mySVNEnvironment, mySVNEnvironment.getEditorCommand(), resultPath); performedEdit = true; } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.CL_NO_EXTERNAL_EDITOR) { mySVNEnvironment.getErr().println(svne.getErrorMessage().getMessage() != null ? svne.getErrorMessage().getMessage() : "No editor found."); } else if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.EXTERNAL_PROGRAM) { mySVNEnvironment.getErr().println(svne.getErrorMessage().getMessage() != null ? svne.getErrorMessage().getMessage() : "Error running editor."); } else { throw svne; } } } else { mySVNEnvironment.getErr().println("Invalid option; there's no merged version to edit."); mySVNEnvironment.getErr().println(); } if (performedEdit) { knowsSmth = true; } } else if ("l".equals(answer)) { if (files.getBaseFile() != null && files.getLocalFile() != null && files.getRepositoryFile() != null && files.getResultFile() != null) { try { SVNCommandUtil.mergeFileExternally(mySVNEnvironment, files.getBasePath(), files.getRepositoryPath(), files.getLocalPath(), files.getResultPath(), files.getWCPath(), null); performedEdit = true; } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.CL_NO_EXTERNAL_MERGE_TOOL) { mySVNEnvironment.getErr().println(svne.getErrorMessage().getMessage() != null ? svne.getErrorMessage().getMessage() : "No merge tool found."); myIsExternalFailed = true; } else if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.EXTERNAL_PROGRAM) { mySVNEnvironment.getErr().println(svne.getErrorMessage().getMessage() != null ? svne.getErrorMessage().getMessage() : "Error running merge tool."); myIsExternalFailed = true; } else { throw svne; } } } else { mySVNEnvironment.getErr().println("Invalid option."); mySVNEnvironment.getErr().println(); } } else if ("r".equals(answer)) { if (knowsSmth) { choice = SVNConflictChoice.MERGED; break; } mySVNEnvironment.getErr().println("Invalid option."); mySVNEnvironment.getErr().println(); } } } else if (conflictDescription.getConflictAction() == SVNConflictAction.ADD && conflictDescription.getConflictReason() == SVNConflictReason.OBSTRUCTED) { String message = "Conflict discovered when trying to add ''{0}''."; message = MessageFormat.format(message, new Object[] { files.getWCFile() }); mySVNEnvironment.getErr().println(message); mySVNEnvironment.getErr().println("An object of the same name already exists."); String prompt = "Select: (p) postpone, (mf) mine-full, (tf) theirs-full, (h) help:"; while (true) { String answer = SVNCommandUtil.prompt(prompt, mySVNEnvironment); if ("h".equals(answer) || "?".equals(answer)) { mySVNEnvironment.getErr().println(" (p) postpone - resolve the conflict later"); mySVNEnvironment.getErr().println(" (mf) mine-full - accept pre-existing item (ignore upstream addition)"); mySVNEnvironment.getErr().println(" (tf) theirs-full - accept incoming item (overwrite pre-existing item)"); mySVNEnvironment.getErr().println(" (h) help - show this help"); mySVNEnvironment.getErr().println(); } if ("p".equals(answer)) { choice = SVNConflictChoice.POSTPONE; break; } if ("mf".equals(answer)) { choice = SVNConflictChoice.MINE_FULL; break; } if ("tf".equals(answer)) { choice = SVNConflictChoice.THEIRS_FULL; break; } } } else { choice = SVNConflictChoice.POSTPONE; } return new SVNConflictResult(choice, null, saveMerged); } private void showConflictedChunks(SVNMergeFileSet files) throws SVNException { byte[] conflictStartMarker = "<<<<<<< MINE (select with 'mc')".getBytes(); byte[] conflictSeparator = "=======".getBytes(); byte[] conflictEndMarker = ">>>>>>> THEIRS (select with 'tc')".getBytes(); byte[] conflictOriginalMarker = "||||||| ORIGINAL".getBytes(); SVNDiffOptions options = new SVNDiffOptions(false, false, true); FSMergerBySequence merger = new FSMergerBySequence(conflictStartMarker, conflictSeparator, conflictEndMarker, conflictOriginalMarker); RandomAccessFile localIS = null; RandomAccessFile latestIS = null; RandomAccessFile baseIS = null; try { localIS = new RandomAccessFile(files.getWCFile(), "r"); latestIS = new RandomAccessFile(files.getRepositoryFile(), "r"); baseIS = new RandomAccessFile(files.getBaseFile(), "r"); QSequenceLineRAData baseData = new QSequenceLineRAFileData(baseIS); QSequenceLineRAData localData = new QSequenceLineRAFileData(localIS); QSequenceLineRAData latestData = new QSequenceLineRAFileData(latestIS); merger.merge(baseData, localData, latestData, options, mySVNEnvironment.getOut(), SVNDiffConflictChoiceStyle.CHOOSE_ONLY_CONFLICTS); } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage()); SVNErrorManager.error(err, e, SVNLogType.WC); } finally { SVNFileUtil.closeFile(localIS); SVNFileUtil.closeFile(baseIS); SVNFileUtil.closeFile(latestIS); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNCommitCommand.java000066400000000000000000000113451177510526000314510ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNBasicClient; import org.tmatesoft.svn.core.wc.SVNCommitClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCommitCommand extends SVNCommand { public SVNCommitCommand() { super("commit", new String[] {"ci"}); } public boolean isCommitter() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.QUIET); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.TARGETS); options.add(SVNOption.NO_UNLOCK); options = SVNOption.addLogMessageOptions(options); options.add(SVNOption.CHANGELIST); options.add(SVNOption.KEEP_CHANGELISTS); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isURL()) { if(SVNBasicClient.isWC17Supported()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is a URL, but URLs cannot be commit targets", targetName); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_BAD_PATH, "Must give local path (not URL) as the target of commit"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } if (targets.isEmpty()) { targets.add("."); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.INFINITY; } SVNCommitClient client = getSVNEnvironment().getClientManager().getCommitClient(); Collection filesList = new ArrayList(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { filesList.add(target.getFile()); } else if (targetName != null) { getSVNEnvironment().getOut().println("Skipped '" + targetName + "'"); } } if (filesList.isEmpty()) { return; } File[] files = (File[]) filesList.toArray(new File[filesList.size()]); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } client.setCommitHandler(getSVNEnvironment()); boolean keepLocks = getSVNEnvironment().getOptions().isKeepLocks(); SVNCommitInfo info = null; try { info = client.doCommit(files, keepLocks, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().getChangelists(), getSVNEnvironment().isKeepChangelist(), getSVNEnvironment().isForce(), depth); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().getRootErrorMessage(); if (err.getErrorCode() == SVNErrorCode.UNKNOWN_CHANGELIST) { SVNErrorManager.error(err, SVNLogType.CLIENT); } throw svne; } if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().printCommitInfo(info); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNConflictAcceptPolicy.java000066400000000000000000000074171177510526000327700ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Map; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.core.internal.util.SVNHashMap; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNConflictAcceptPolicy { public static final SVNConflictAcceptPolicy INVALID = new SVNConflictAcceptPolicy("invalid"); public static final SVNConflictAcceptPolicy UNSPECIFIED = new SVNConflictAcceptPolicy("unspecified"); /** * Resolve the conflict with the pre-conflict base file. */ public static final SVNConflictAcceptPolicy BASE = new SVNConflictAcceptPolicy("base"); /** * Resolve the conflict with the pre-conflict working copy file. */ public static final SVNConflictAcceptPolicy MINE_CONFLICT = new SVNConflictAcceptPolicy("mine-conflict"); public static final SVNConflictAcceptPolicy MINE_FULL = new SVNConflictAcceptPolicy("mine-full"); public static final SVNConflictAcceptPolicy WORKING = new SVNConflictAcceptPolicy("working"); /** * Resolve the conflict with the post-conflict base file. */ public static final SVNConflictAcceptPolicy THEIRS_CONFLICT = new SVNConflictAcceptPolicy("theirs-conflict"); public static final SVNConflictAcceptPolicy THEIRS_FULL = new SVNConflictAcceptPolicy("theirs-full"); public static final SVNConflictAcceptPolicy POSTPONE = new SVNConflictAcceptPolicy("postpone"); public static final SVNConflictAcceptPolicy EDIT = new SVNConflictAcceptPolicy("edit"); public static final SVNConflictAcceptPolicy LAUNCH = new SVNConflictAcceptPolicy("launch"); private String myName; private SVNConflictAcceptPolicy(String name) { myName = name; } public String toString() { return myName; } public static SVNConflictAcceptPolicy fromString(String accept) { if (POSTPONE.myName.equals(accept) || "p".equals(accept) || ":-P".equals(accept)) { return SVNConflictAcceptPolicy.POSTPONE; } else if (BASE.myName.equals(accept)) { return SVNConflictAcceptPolicy.BASE; } else if (MINE_CONFLICT.myName.equals(accept) || "mc".equals(accept) || "X-)".equals(accept)) { return SVNConflictAcceptPolicy.MINE_CONFLICT; } else if (THEIRS_CONFLICT.myName.equals(accept) || "tc".equals(accept) || "X-(".equals(accept)) { return SVNConflictAcceptPolicy.THEIRS_CONFLICT; } else if (EDIT.myName.equals(accept) || "e".equals(accept) || ":-E".equals(accept)) { return SVNConflictAcceptPolicy.EDIT; } else if (LAUNCH.myName.equals(accept) || "l".equals(accept) || ":-l".equals(accept)) { return SVNConflictAcceptPolicy.LAUNCH; } else if (MINE_FULL.myName.equals(accept) || "mf".equals(accept) || ":-)".equals(accept)) { return SVNConflictAcceptPolicy.MINE_FULL; } else if (THEIRS_FULL.myName.equals(accept) || "tf".equals(accept) || ":-(".equals(accept)) { return SVNConflictAcceptPolicy.THEIRS_FULL; } else if (WORKING.myName.equals(accept)) { return SVNConflictAcceptPolicy.WORKING; } return SVNConflictAcceptPolicy.INVALID; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNCopyCommand.java000066400000000000000000000110261177510526000311270ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNCopyClient; import org.tmatesoft.svn.core.wc.SVNCopySource; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNCopyCommand extends SVNCommand { public SVNCopyCommand() { super("copy", new String[] {"cp"}); } public boolean isCommitter() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.QUIET); options.add(SVNOption.IGNORE_EXTERNALS); options.add(SVNOption.PARENTS); options = SVNOption.addLogMessageOptions(options); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(null, true); if (targets.size() < 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNPath dst = new SVNPath((String) targets.remove(targets.size() - 1)); if (!dst.isURL()) { if (getSVNEnvironment().getMessage() != null || getSVNEnvironment().getFileData() != null || getSVNEnvironment().getRevisionProperties() != null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_UNNECESSARY_LOG_MESSAGE, "Local, non-commit operations do not take a log message or revision properties"), SVNLogType.CLIENT); } } Collection sources = new ArrayList(); boolean sourceIsURL = false; for (int i = 0; i < targets.size(); i++) { String targetName = (String) targets.get(i); SVNPath source = new SVNPath(targetName, true); if (i == 0) { sourceIsURL = source.isURL(); } if (source.isURL()) { sources.add(new SVNCopySource(source.getPegRevision(), getSVNEnvironment().getStartRevision(), source.getURL())); } else { sources.add(new SVNCopySource(source.getPegRevision(), getSVNEnvironment().getStartRevision(), source.getFile())); } } SVNCopyClient client = getSVNEnvironment().getClientManager().getCopyClient(); if (!sourceIsURL && !dst.isURL()) { if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } } else if (!sourceIsURL && dst.isURL()){ SVNNotifyPrinter printer = new SVNNotifyPrinter(getSVNEnvironment()); printer.setWcToReposCopy(true); client.setEventHandler(printer); } else if (sourceIsURL && !dst.isURL()) { if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment(), true, false, false)); } } client.setCommitHandler(getSVNEnvironment()); SVNCopySource[] copySources = (SVNCopySource[]) sources.toArray(new SVNCopySource[sources.size()]); if (dst.isURL()) { SVNCommitInfo info = client.doCopy(copySources, dst.getURL(), false, getSVNEnvironment().isParents(), false, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties()); if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().printCommitInfo(info); } } else { client.doCopy(copySources, dst.getFile(), false, getSVNEnvironment().isParents(), false); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNDeleteCommand.java000066400000000000000000000122401177510526000314160ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNCommitClient; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDeleteCommand extends SVNCommand { public SVNDeleteCommand() { super("delete", new String[] {"del", "remove", "rm"}); } public boolean isCommitter() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.FORCE); options.add(SVNOption.QUIET); options.add(SVNOption.TARGETS); options = SVNOption.addLogMessageOptions(options); options.add(SVNOption.KEEP_LOCAL); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } boolean hasURLs = false; boolean hasPaths = false; for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); if (!SVNCommandUtil.isURL(targetName)) { if (getSVNEnvironment().getMessage() != null || getSVNEnvironment().getFileData() != null || getSVNEnvironment().getRevisionProperties() != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_UNNECESSARY_LOG_MESSAGE, "Local, non-commit operations do not take a log message or revision properties"); SVNErrorManager.error(err, SVNLogType.CLIENT); } hasPaths = true; } else { hasURLs = true; } } if (hasURLs && hasPaths) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Specify either URLs or local paths, not both"), SVNLogType.CLIENT); } if (hasURLs) { SVNCommitClient client = getSVNEnvironment().getClientManager().getCommitClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } client.setCommitHandler(getSVNEnvironment()); SVNURL[] urls = new SVNURL[targets.size()]; for (int i = 0; i < targets.size(); i++) { String url = (String) targets.get(i); urls[i] = SVNURL.parseURIEncoded(url); } try { SVNCommitInfo info = client.doDelete(urls, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties()); if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().printCommitInfo(info); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else { SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } try { for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); client.doDelete(target.getFile(), getSVNEnvironment().isForce(), !getSVNEnvironment().isKeepLocal(), false); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (err != null) { SVNErrorCode code = err.getErrorCode(); if (code == SVNErrorCode.UNVERSIONED_RESOURCE || code == SVNErrorCode.CLIENT_MODIFIED) { err = err.wrap("Use --force to override this restriction"); } } SVNErrorManager.error(err, SVNLogType.CLIENT); } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNDiffCommand.java000066400000000000000000000360151177510526000310720ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc2.ng.SvnDiffGenerator; import org.tmatesoft.svn.core.internal.wc2.ng.SvnNewDiffGenerator; import org.tmatesoft.svn.core.wc.ISVNDiffStatusHandler; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.core.wc.SVNDiffStatus; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDiffCommand extends SVNXMLCommand implements ISVNDiffStatusHandler { public SVNDiffCommand() { super("diff", new String[] {"di"}); } public boolean acceptsRevisionRange() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.CHANGE); options.add(SVNOption.OLD); options.add(SVNOption.NEW); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.DIFF_CMD); options.add(SVNOption.EXTENSIONS); options.add(SVNOption.NO_DIFF_DELETED); options.add(SVNOption.NOTICE_ANCESTRY); options.add(SVNOption.SHOW_COPIES_AS_ADDS); options.add(SVNOption.SUMMARIZE); options.add(SVNOption.CHANGELIST); options.add(SVNOption.FORCE); options.add(SVNOption.XML); options.add(SVNOption.GIT_DIFF_FORMAT); return options; } public void run() throws SVNException { if (getSVNEnvironment().isXML()) { if (!getSVNEnvironment().isSummarize()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'--xml' option only valid with '--summarize' option"); SVNErrorManager.error(err, SVNLogType.CLIENT); } printXMLHeader("diff"); StringBuffer buffer = openXMLTag("paths", SVNXMLUtil.XML_STYLE_NORMAL, null, null); getSVNEnvironment().getOut().print(buffer.toString()); } List targets = new ArrayList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); SVNPath oldTarget = null; SVNPath newTarget = null; SVNRevision start = getSVNEnvironment().getStartRevision(); SVNRevision end = getSVNEnvironment().getEndRevision(); boolean peggedDiff = false; if (targets.size() == 2 && getSVNEnvironment().getOldTarget() == null && getSVNEnvironment().getNewTarget() == null && SVNCommandUtil.isURL((String) targets.get(0)) && SVNCommandUtil.isURL((String) targets.get(1)) && getSVNEnvironment().getStartRevision() == SVNRevision.UNDEFINED && getSVNEnvironment().getEndRevision() == SVNRevision.UNDEFINED) { oldTarget = new SVNPath((String) targets.get(0), true); newTarget = new SVNPath((String) targets.get(1), true); start = oldTarget.getPegRevision(); end = newTarget.getPegRevision(); targets.clear(); if (start == SVNRevision.UNDEFINED) { start = SVNRevision.HEAD; } if (end == SVNRevision.UNDEFINED) { end = SVNRevision.HEAD; } } else if (getSVNEnvironment().getOldTarget() != null) { targets.clear(); targets.add(getSVNEnvironment().getOldTarget()); targets.add(getSVNEnvironment().getNewTarget() != null ? getSVNEnvironment().getNewTarget() : getSVNEnvironment().getOldTarget()); oldTarget = new SVNPath((String) targets.get(0), true); newTarget = new SVNPath((String) targets.get(1), true); start = getSVNEnvironment().getStartRevision(); end = getSVNEnvironment().getEndRevision(); if (oldTarget.getPegRevision() != SVNRevision.UNDEFINED) { start = oldTarget.getPegRevision(); } if (newTarget.getPegRevision() != SVNRevision.UNDEFINED) { end = newTarget.getPegRevision(); } if (start == SVNRevision.UNDEFINED) { start = oldTarget.isURL() ? SVNRevision.HEAD : SVNRevision.BASE; } if (end == SVNRevision.UNDEFINED) { end = newTarget.isURL() ? SVNRevision.HEAD : SVNRevision.WORKING; } targets = getSVNEnvironment().combineTargets(null, true); } else if (getSVNEnvironment().getNewTarget() != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'--new' option only valid with '--old' option"); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { if (targets.isEmpty()) { targets.add(""); } oldTarget = new SVNPath(""); newTarget = new SVNPath(""); boolean hasURLs = false; boolean hasWCs = false; for(int i = 0; i < targets.size(); i++) { SVNPath target = new SVNPath((String) targets.get(i)); hasURLs |= target.isURL(); hasWCs |= target.isFile(); } if (hasURLs && hasWCs) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Target lists to diff may not contain both working copy paths and URLs"); SVNErrorManager.error(err, SVNLogType.CLIENT); } start = getSVNEnvironment().getStartRevision(); end = getSVNEnvironment().getEndRevision(); if (start == SVNRevision.UNDEFINED && hasWCs) { start = SVNRevision.BASE; } if (end == SVNRevision.UNDEFINED) { end = hasWCs ? SVNRevision.WORKING : SVNRevision.HEAD; } peggedDiff = (start != SVNRevision.BASE && start != SVNRevision.WORKING) || (end != SVNRevision.BASE && end != SVNRevision.WORKING); } if (targets.isEmpty()) { targets.add(""); } SVNDiffClient client = getSVNEnvironment().getClientManager().getDiffClient(); SVNCommandEnvironment environment = (SVNCommandEnvironment) getEnvironment(); client.setShowCopiesAsAdds(environment.isShowCopiesAsAdds()); client.setGitDiffFormat(environment.isGitDiffFormat()); SvnNewDiffGenerator generator = createDiffGenerator(getSVNEnvironment()); client.setDiffGenerator(generator); PrintStream ps = getSVNEnvironment().getOut(); Collection changeLists = getSVNEnvironment().getChangelistsCollection(); for(int i = 0; i < targets.size(); i++) { String targetName = (String) targets.get(i); if (!peggedDiff) { SVNPath target1 = new SVNPath(SVNPathUtil.append(oldTarget.getTarget(), targetName)); SVNPath target2 = new SVNPath(SVNPathUtil.append(newTarget.getTarget(), targetName)); if (getSVNEnvironment().isSummarize()) { if (target1.isURL() && target2.isURL()) { client.doDiffStatus(target1.getURL(), start, target2.getURL(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), this); } else if (target1.isURL()) { client.doDiffStatus(target1.getURL(), start, target2.getFile(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), this); } else if (target2.isURL()) { client.doDiffStatus(target1.getFile(), start, target2.getURL(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), this); } else { client.doDiffStatus(target1.getFile(), start, target2.getFile(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), this); } } else { if (target1.isURL() && target2.isURL()) { client.doDiff(target1.getURL(), start, target2.getURL(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), ps); } else if (target1.isURL()) { client.doDiff(target1.getURL(), start, target2.getFile(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), ps, changeLists); } else if (target2.isURL()) { client.doDiff(target1.getFile(), start, target2.getURL(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), ps, changeLists); } else { client.doDiff(target1.getFile(), start, target2.getFile(), end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), ps, changeLists); } } } else { SVNPath target = new SVNPath(targetName, true); SVNRevision pegRevision = target.getPegRevision(); if (pegRevision == SVNRevision.UNDEFINED) { pegRevision = target.isURL() ? SVNRevision.HEAD : SVNRevision.WORKING; } if (getSVNEnvironment().isSummarize()) { if (target.isURL()) { client.doDiffStatus(target.getURL(), start, end, pegRevision, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), this); } else { client.doDiffStatus(target.getFile(), start, end, pegRevision, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), this); } } else { if (target.isURL()) { client.doDiff(target.getURL(), pegRevision, start, end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), ps); } else { client.doDiff(target.getFile(), pegRevision, start, end, getSVNEnvironment().getDepth(), getSVNEnvironment().isNoticeAncestry(), ps, changeLists); } } } } if (getSVNEnvironment().isXML()) { StringBuffer buffer = closeXMLTag("paths", null); getSVNEnvironment().getOut().print(buffer.toString()); printXMLFooter("diff"); } } static SvnNewDiffGenerator createDiffGenerator(SVNCommandEnvironment svnEnvironment) throws SVNException { SvnDiffGenerator diffGenerator = new SvnDiffGenerator(); if (svnEnvironment.getDiffCommand() != null) { diffGenerator.setExternalDiffCommand(svnEnvironment.getDiffCommand()); diffGenerator.setRawDiffOptions((List) svnEnvironment.getExtensions()); } else { diffGenerator.setDiffOptions(svnEnvironment.getDiffOptions()); } diffGenerator.setDiffDeleted(!svnEnvironment.isNoDiffDeleted()); diffGenerator.setForcedBinaryDiff(svnEnvironment.isForce()); diffGenerator.setBasePath(new File("").getAbsoluteFile()); diffGenerator.setFallbackToAbsolutePath(true); diffGenerator.setOptions(svnEnvironment.getOptions()); diffGenerator.setDiffDeleted(!svnEnvironment.isNoDiffDeleted()); return new SvnNewDiffGenerator(diffGenerator); } public void handleDiffStatus(SVNDiffStatus diffStatus) throws SVNException { if (diffStatus.getModificationType() == SVNStatusType.STATUS_NONE && !diffStatus.isPropertiesModified()) { return; } String path = diffStatus.getPath(); if (diffStatus.getFile() != null) { path = getSVNEnvironment().getRelativePath(diffStatus.getFile()); path = SVNCommandUtil.getLocalPath(path); } else if (diffStatus.getURL() != null) { path = diffStatus.getURL().toString(); } else { path = diffStatus.getPath(); if (!SVNCommandUtil.isURL(path)) { path = SVNCommandUtil.getLocalPath(path); } } if (getSVNEnvironment().isXML()) { StringBuffer buffer = new StringBuffer(); Map attrs = new SVNHashMap(); attrs.put("kind", diffStatus.getKind().toString()); String modificationKind = "none"; if (diffStatus.getModificationType() == SVNStatusType.STATUS_MODIFIED) { modificationKind = "modified"; } else if (diffStatus.getModificationType() == SVNStatusType.STATUS_ADDED) { modificationKind = "added"; } else if (diffStatus.getModificationType() == SVNStatusType.STATUS_DELETED) { modificationKind = "deleted"; } attrs.put("item", modificationKind); attrs.put("props", diffStatus.isPropertiesModified() ? "modified" : "none"); buffer = openXMLTag("path", SVNXMLUtil.XML_STYLE_PROTECT_CDATA, attrs, buffer); buffer.append(SVNEncodingUtil.xmlEncodeCDATA(path)); buffer = closeXMLTag("path", buffer); getSVNEnvironment().getOut().print(buffer.toString()); } else { getSVNEnvironment().getOut().print(diffStatus.getModificationType().getCode() + (diffStatus.isPropertiesModified() ? "M" : " ") + " " + path + "\n"); getSVNEnvironment().getOut().flush(); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNExportCommand.java000066400000000000000000000100151177510526000314730ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNUpdateClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNExportCommand extends SVNCommand { public SVNExportCommand() { super("export", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.QUIET); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.FORCE); options.add(SVNOption.NATIVE_EOL); options.add(SVNOption.IGNORE_EXTERNALS); options.add(SVNOption.IGNORE_KEYWORDS); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(new ArrayList(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } if (targets.size() > 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR), SVNLogType.CLIENT); } SVNPath from = new SVNPath((String) targets.get(0), true); SVNRevision pegRevision = from.getPegRevision(); String to; if (targets.size() == 1) { to = SVNPathUtil.tail(from.getTarget()); if (from.isURL()) { to = SVNEncodingUtil.uriDecode(to); } } else { to = (String) targets.get(1); } SVNUpdateClient client = getSVNEnvironment().getClientManager().getUpdateClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment(), false, true, false)); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.INFINITY; } try { SVNPath dst = new SVNPath(to); String eol = getSVNEnvironment().getNativeEOL(); SVNRevision revision = getSVNEnvironment().getStartRevision(); client.setExportExpandsKeywords(!getSVNEnvironment().isIgnoreKeywords()); if (from.isFile()) { client.doExport(from.getFile(), dst.getFile(), pegRevision, revision, eol, getSVNEnvironment().isForce(), depth); } else { client.doExport(from.getURL(), dst.getFile(), pegRevision, revision, eol, getSVNEnvironment().isForce(), depth); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (err != null && err.getErrorCode() == SVNErrorCode.WC_OBSTRUCTED_UPDATE) { err = err.wrap("Destination directory exists; please remove the directory or use --force to overwrite"); } SVNErrorManager.error(err, SVNLogType.CLIENT); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNHelpCommand.java000066400000000000000000000107531177510526000311130ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.text.MessageFormat; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNHelpCommand extends SVNCommand { private static final String GENERIC_HELP_HEADER = "usage: {0} [options] [args]\n" + "Subversion command-line client, version {1}.\n" + "Type ''{0} help '' for help on a specific subcommand.\n" + "Type ''{0} --version'' to see the program version and RA modules\n" + " or ''{0} --version --quiet'' to see just the version number.\n" + "\n" + "Most subcommands take file and/or directory arguments, recursing\n" + "on the directories. If no arguments are supplied to such a\n" + "command, it recurses on the current directory (inclusive) by default.\n" + "\n" + "Available subcommands:"; private static final String GENERIC_HELP_FOOTER = "SVNKit is a pure Java (TM) version of Subversion - a tool for version control.\n" + "For additional information, see http://svnkit.com/\n"; private static final String VERSION_HELP_FOOTER = "\nThe following repository access (RA) modules are available:\n\n" + "* org.tmatesoft.svn.core.internal.io.dav : Module for accessing a repository via WebDAV protocol.\n" + " - handles 'http' scheme\n" + " - handles 'https' scheme\n" + "* org.tmatesoft.svn.core.internal.io.svn: Module for accessing a repository using the svn network protocol.\n" + " - handles 'svn' scheme\n" + "* org.tmatesoft.svn.core.internal.io.fs: Module for accessing a repository on local disk.\n" + " - handles 'file' scheme (only FSFS repositories are supported)\n"; public SVNHelpCommand() { super("help", new String[] {"?", "h"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); return options; } public static void printBasicUsage(String programName) { System.err.println(MessageFormat.format("Type ''{0} help'' for usage.", new Object[] {programName})); } public void run() throws SVNException { if (!getSVNEnvironment().getArguments().isEmpty()) { for (Iterator commands = getSVNEnvironment().getArguments().iterator(); commands.hasNext();) { String commandName = (String) commands.next(); AbstractSVNCommand command = AbstractSVNCommand.getCommand(commandName); if (command == null) { getSVNEnvironment().getErr().println("\"" + commandName + "\": unknown command.\n"); continue; } String help = SVNCommandUtil.getCommandHelp(command, getEnvironment().getProgramName(), true); getSVNEnvironment().getOut().println(help); getSVNEnvironment().getOut().println(); } } else if (getSVNEnvironment().isVersion()) { String version = SVNCommandUtil.getVersion(getEnvironment(), getSVNEnvironment().isQuiet()); getEnvironment().getOut().println(version); if (!getSVNEnvironment().isQuiet()) { getEnvironment().getOut().println(VERSION_HELP_FOOTER); } } else if (getSVNEnvironment().getArguments().isEmpty()) { String help = SVNCommandUtil.getGenericHelp(getEnvironment().getProgramName(), GENERIC_HELP_HEADER, GENERIC_HELP_FOOTER, null); getSVNEnvironment().getOut().print(help); } else { String message = MessageFormat.format("Type ''{0} help'' for usage.", new Object[] {getSVNEnvironment().getProgramName()}); getSVNEnvironment().getOut().println(message); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNImportCommand.java000066400000000000000000000072011177510526000314670ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNCommitClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNImportCommand extends SVNCommand { public SVNImportCommand() { super("import", null); } public boolean isCommitter() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.QUIET); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.AUTOPROPS); options.add(SVNOption.FORCE); options.add(SVNOption.NO_AUTOPROPS); options = SVNOption.addLogMessageOptions(options); options.add(SVNOption.NO_IGNORE); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(new ArrayList(), true); SVNPath url = null; SVNPath src = null; if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Repository URL required when importing"), SVNLogType.CLIENT); } else if (targets.size() > 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Too many arguments to import command"), SVNLogType.CLIENT); } else if (targets.size() == 1) { src = new SVNPath(""); url = new SVNPath((String) targets.get(0)); } else { src = new SVNPath((String) targets.get(0)); url = new SVNPath((String) targets.get(1)); } if (!url.isURL()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Invalid URL ''{0}''", url.getTarget()), SVNLogType.CLIENT); } SVNCommitClient client = getSVNEnvironment().getClientManager().getCommitClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.INFINITY; } client.setCommitHandler(getSVNEnvironment()); SVNCommitInfo info = client.doImport(src.getFile(), url.getURL(), getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties(), !getSVNEnvironment().isNoIgnore(), getSVNEnvironment().isForce(), depth); if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().printCommitInfo(info); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNInfoCommand.java000066400000000000000000000510261177510526000311140ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNConflictVersion; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.SVNTreeConflictUtil; import org.tmatesoft.svn.core.wc.ISVNInfoHandler; import org.tmatesoft.svn.core.wc.SVNConflictAction; import org.tmatesoft.svn.core.wc.SVNConflictReason; import org.tmatesoft.svn.core.wc.SVNInfo; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNTreeConflictDescription; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNInfoCommand extends SVNXMLCommand implements ISVNInfoHandler { public SVNInfoCommand() { super("info", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.TARGETS); options.add(SVNOption.INCREMENTAL); options.add(SVNOption.XML); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { List targets = new ArrayList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { targets.add(""); } if (getSVNEnvironment().isXML()) { if (!getSVNEnvironment().isIncremental()) { printXMLHeader("info"); } } else if (getSVNEnvironment().isIncremental()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'incremental' option only valid in XML mode"), SVNLogType.CLIENT); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); boolean seenNonExistingTargets = false; for(int i = 0; i < targets.size(); i++) { String targetName = (String) targets.get(i); SVNPath target = new SVNPath(targetName, true); SVNRevision pegRevision = target.getPegRevision(); if (target.isURL() && pegRevision == SVNRevision.UNDEFINED) { pegRevision = SVNRevision.HEAD; } try { if (target.isFile()) { client.doInfo(target.getFile(), pegRevision, getSVNEnvironment().getStartRevision(), depth, getSVNEnvironment().getChangelistsCollection(), this); } else { client.doInfo(target.getURL(), pegRevision, getSVNEnvironment().getStartRevision(), depth, this); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.UNVERSIONED_RESOURCE) { getSVNEnvironment().getErr().print(SVNCommandUtil.getLocalPath(target.getTarget()) + ": (Not a versioned resource)\n\n"); } else { getSVNEnvironment().handleWarning(err, new SVNErrorCode[] {SVNErrorCode.RA_ILLEGAL_URL, SVNErrorCode.WC_PATH_NOT_FOUND}, getSVNEnvironment().isQuiet()); getSVNEnvironment().getErr().println(); seenNonExistingTargets = true; } } } if (getSVNEnvironment().isXML() && !getSVNEnvironment().isIncremental()) { printXMLFooter("info"); } if (seenNonExistingTargets) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not display info for all targets because some targets don't exist"), SVNLogType.CLIENT); } } public void handleInfo(SVNInfo info) throws SVNException { if (!getSVNEnvironment().isXML()) { printInfo(info); } else { printInfoXML(info); } } protected void printInfo(SVNInfo info) { StringBuffer buffer = new StringBuffer(); String path = null; if (info.getFile() != null) { path = getSVNEnvironment().getRelativePath(info.getFile()); path = SVNCommandUtil.getLocalPath(path); } else { path = info.getPath(); if ("".equals(path) && info.getURL() != null) { path = SVNPathUtil.tail(info.getURL().getPath()); } } buffer.append("Path: " + path + "\n"); if (info.getKind() != SVNNodeKind.DIR) { buffer.append("Name: " + SVNPathUtil.tail(path.replace(File.separatorChar, '/')) + "\n"); } if (info.getWorkingCopyRoot() != null) { buffer.append("Working Copy Root Path: " + SVNPathUtil.validateFilePath(info.getWorkingCopyRoot().getAbsolutePath())+ "\n"); } buffer.append("URL: " + info.getURL() + "\n"); if (info.getRepositoryRootURL() != null) { buffer.append("Repository Root: " + info.getRepositoryRootURL() + "\n"); } if (info.getRepositoryUUID() != null) { buffer.append("Repository UUID: " + info.getRepositoryUUID() + "\n"); } if (info.getRevision() != null && info.getRevision().isValid()) { buffer.append("Revision: " + info.getRevision() + "\n"); } String kind = info.getKind() == SVNNodeKind.DIR ? "directory" : (info.getKind() != null ? info.getKind().toString() : "none"); buffer.append("Node Kind: " + kind + "\n"); if (!info.isRemote()) { if (info.getSchedule() == null) { buffer.append("Schedule: normal\n"); } else { buffer.append("Schedule: " + info.getSchedule() + "\n"); } if (info.getDepth() != null) { if (info.getDepth() != SVNDepth.UNKNOWN && info.getDepth() != SVNDepth.INFINITY) { buffer.append("Depth: " + info.getDepth() + "\n"); } } if (info.getCopyFromURL() != null) { buffer.append("Copied From URL: " + info.getCopyFromURL() + "\n"); } if (info.getCopyFromRevision() != null && info.getCopyFromRevision().getNumber() >= 0) { buffer.append("Copied From Rev: " + info.getCopyFromRevision() + "\n"); } } if (info.getAuthor() != null) { buffer.append("Last Changed Author: " + info.getAuthor() + "\n"); } if (info.getCommittedRevision() != null && info.getCommittedRevision().getNumber() >= 0) { buffer.append("Last Changed Rev: " + info.getCommittedRevision() + "\n"); } if (info.getCommittedDate() != null) { buffer.append("Last Changed Date: " + SVNDate.formatHumanDate(info.getCommittedDate(), getSVNEnvironment().getClientManager().getOptions()) + "\n"); } if (!info.isRemote()) { if (info.getTextTime() != null) { buffer.append("Text Last Updated: " + SVNDate.formatHumanDate(info.getTextTime(), getSVNEnvironment().getClientManager().getOptions()) + "\n"); } if (info.getPropTime() != null) { buffer.append("Properties Last Updated: " + SVNDate.formatHumanDate(info.getPropTime(), getSVNEnvironment().getClientManager().getOptions()) + "\n"); } if (info.getChecksum() != null) { buffer.append("Checksum: " + info.getChecksum() + "\n"); } if (info.getConflictOldFile() != null) { String cpath = getSVNEnvironment().getRelativePath(info.getConflictOldFile()); cpath = SVNCommandUtil.getLocalPath(cpath); buffer.append("Conflict Previous Base File: " + cpath + "\n"); } if (info.getConflictWrkFile() != null) { String cpath = getSVNEnvironment().getRelativePath(info.getConflictWrkFile()); cpath = SVNCommandUtil.getLocalPath(cpath); buffer.append("Conflict Previous Working File: " + cpath + "\n"); } if (info.getConflictNewFile() != null) { String cpath = getSVNEnvironment().getRelativePath(info.getConflictNewFile()); cpath = SVNCommandUtil.getLocalPath(cpath); buffer.append("Conflict Current Base File: " + cpath + "\n"); } if (info.getPropConflictFile() != null) { String cpath = getSVNEnvironment().getRelativePath(info.getPropConflictFile()); cpath = SVNCommandUtil.getLocalPath(cpath); buffer.append("Conflict Properties File: " + cpath + "\n"); } } if (info.getLock() != null) { SVNLock lock = info.getLock(); if (lock.getID() != null) { buffer.append("Lock Token: " + lock.getID() + "\n"); } if (lock.getOwner() != null) { buffer.append("Lock Owner: " + lock.getOwner() + "\n"); } if (lock.getCreationDate() != null && lock.getCreationDate().getTime() != 0) { buffer.append("Lock Created: " + SVNDate.formatHumanDate(lock.getCreationDate(), getSVNEnvironment().getClientManager().getOptions()) + "\n"); } if (lock.getExpirationDate() != null && lock.getExpirationDate().getTime() != 0) { buffer.append("Lock Expires: " + SVNDate.formatHumanDate(lock.getExpirationDate(), getSVNEnvironment().getClientManager().getOptions()) + "\n"); } if (lock.getComment() != null) { buffer.append("Lock Comment "); int lineCount = SVNCommandUtil.getLinesCount(lock.getComment()); buffer.append(lineCount > 1 ? "(" + lineCount + " lines)" : "(1 line)"); buffer.append(":\n"); buffer.append(lock.getComment()); buffer.append("\n"); } } if (info.getChangelistName() != null) { buffer.append("Changelist: " + info.getChangelistName() + "\n"); } if (info.getTreeConflict() != null) { SVNTreeConflictDescription tc = info.getTreeConflict(); String description = SVNTreeConflictUtil.getHumanReadableConflictDescription(tc); buffer.append("Tree conflict: " + description + "\n"); SVNConflictVersion left = tc.getSourceLeftVersion(); buffer.append(" Source left: " + SVNTreeConflictUtil.getHumanReadableConflictVersion(left) + "\n"); SVNConflictVersion right = tc.getSourceRightVersion(); buffer.append(" Source right: " + SVNTreeConflictUtil.getHumanReadableConflictVersion(right) + "\n"); } buffer.append("\n"); getSVNEnvironment().getOut().print(buffer.toString()); } protected void printInfoXML(SVNInfo info) { StringBuffer buffer = new StringBuffer(); String path = null; if (info.getFile() != null) { path = getSVNEnvironment().getRelativePath(info.getFile()); path = SVNCommandUtil.getLocalPath(path); } else { path = info.getPath(); } Map attrs = new LinkedHashMap(); attrs.put("kind", info.getKind().toString()); attrs.put("path", path); attrs.put("revision", info.getRevision() != SVNRevision.UNDEFINED ? info.getRevision().toString() : "Resource is not under version control."); buffer = openXMLTag("entry", SVNXMLUtil.XML_STYLE_NORMAL, attrs, buffer); String url = info.getURL() != null ? info.getURL().toString() : null; buffer = openCDataTag("url", url, buffer); String rootURL = info.getRepositoryRootURL() != null ? info.getRepositoryRootURL().toString() : null; String uuid = info.getRepositoryUUID(); if (rootURL != null || uuid != null) { buffer = openXMLTag("repository", SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); buffer = openCDataTag("root", rootURL, buffer); buffer = openCDataTag("uuid", uuid, buffer); buffer = closeXMLTag("repository", buffer); } if (info.getFile() != null) { buffer = openXMLTag("wc-info", SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); if (info.getWorkingCopyRoot() != null) { buffer = openCDataTag("wcroot-abspath", SVNPathUtil.validateFilePath(info.getWorkingCopyRoot().getAbsolutePath()), buffer); } String schedule = info.getSchedule(); if (schedule == null || "".equals(schedule)) { schedule = "normal"; } buffer = openCDataTag("schedule", schedule, buffer); if (info.getDepth() != null) { SVNDepth depth = info.getDepth(); if (depth == SVNDepth.UNKNOWN && info.getKind() == SVNNodeKind.FILE) { depth = SVNDepth.INFINITY; } buffer = openCDataTag("depth", depth.getName(), buffer); } if (info.getCopyFromURL() != null) { buffer = openCDataTag("copy-from-url", info.getCopyFromURL().toString(), buffer); } if (info.getCopyFromRevision() != null && info.getCopyFromRevision().isValid()) { buffer = openCDataTag("copy-from-rev", info.getCopyFromRevision().toString(), buffer); } if (info.getTextTime() != null) { buffer = openCDataTag("text-updated", ((SVNDate) info.getTextTime()).format(), buffer); } if (info.getPropTime() != null) { buffer = openCDataTag("prop-updated", ((SVNDate) info.getPropTime()).format(), buffer); } buffer = openCDataTag("checksum", info.getChecksum(), buffer); buffer = openCDataTag("changelist", info.getChangelistName(), buffer); buffer = closeXMLTag("wc-info", buffer); } if (info.getAuthor() != null || info.getCommittedRevision().isValid() || info.getCommittedDate() != null) { openXMLTag("commit", SVNXMLUtil.XML_STYLE_NORMAL, "revision", info.getCommittedRevision().toString(), buffer); buffer = openCDataTag("author", info.getAuthor(), buffer); if (info.getCommittedDate() != null) { buffer = openCDataTag("date", ((SVNDate) info.getCommittedDate()).format(), buffer); } buffer = closeXMLTag("commit", buffer); } if (info.getConflictNewFile() != null || info.getConflictOldFile() != null || info.getConflictWrkFile() != null || info.getPropConflictFile() != null) { buffer = openXMLTag("conflict", SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); if (info.getConflictOldFile() != null) { buffer = openCDataTag("prev-base-file", info.getConflictOldFile().getName(), buffer); } if (info.getConflictWrkFile() != null) { buffer = openCDataTag("prev-wc-file", info.getConflictWrkFile().getName(), buffer); } if (info.getConflictNewFile() != null) { buffer = openCDataTag("cur-base-file", info.getConflictNewFile().getName(), buffer); } if (info.getPropConflictFile() != null) { buffer = openCDataTag("prop-file", info.getPropConflictFile().getName(), buffer); } buffer = closeXMLTag("conflict", buffer); } if (info.getLock() != null) { SVNLock lock = info.getLock(); buffer = openXMLTag("lock", SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); buffer = openCDataTag("token", lock.getID(), buffer); buffer = openCDataTag("owner", lock.getOwner(), buffer); buffer = openCDataTag("comment", lock.getComment(), buffer); if (lock.getCreationDate() != null) { buffer = openCDataTag("created", ((SVNDate) lock.getCreationDate()).format(), buffer); } if (lock.getExpirationDate() != null) { buffer = openCDataTag("expires", ((SVNDate) lock.getExpirationDate()).format(), buffer); } buffer = closeXMLTag("lock", buffer); } if (info.getTreeConflict() != null) { SVNTreeConflictDescription tc = info.getTreeConflict(); Map attributes = new SVNHashMap(); attributes.put("victim", tc.getPath().getName()); attributes.put("kind", tc.getNodeKind().toString()); attributes.put("operation", tc.getOperation().getName()); if (tc.getConflictAction() == SVNConflictAction.EDIT) { attributes.put("action", "edit"); } else if (tc.getConflictAction() == SVNConflictAction.ADD) { attributes.put("action", "add"); } else if (tc.getConflictAction() == SVNConflictAction.DELETE) { attributes.put("action", "delete"); } if (tc.getConflictReason() == SVNConflictReason.EDITED) { attributes.put("reason", "edit"); } else if (tc.getConflictReason() == SVNConflictReason.OBSTRUCTED) { attributes.put("reason", "obstruction"); } else if (tc.getConflictReason() == SVNConflictReason.DELETED) { attributes.put("reason", "delete"); } else if (tc.getConflictReason() == SVNConflictReason.ADDED) { attributes.put("reason", "add"); } else if (tc.getConflictReason() == SVNConflictReason.MISSING) { attributes.put("reason", "missing"); } else if (tc.getConflictReason() == SVNConflictReason.UNVERSIONED) { attributes.put("reason", "unversioned"); } buffer = openXMLTag("tree-conflict", SVNXMLUtil.XML_STYLE_NORMAL, attributes, buffer); SVNConflictVersion left = tc.getSourceLeftVersion(); if (left != null) { buffer = printConflictVersionXML(left, "source-left", buffer); } SVNConflictVersion right = tc.getSourceLeftVersion(); if (right != null) { buffer = printConflictVersionXML(right, "source-right", buffer); } buffer = closeXMLTag("tree-conflict", buffer); } buffer = closeXMLTag("entry", buffer); getSVNEnvironment().getOut().print(buffer.toString()); } private StringBuffer printConflictVersionXML(SVNConflictVersion version, String name, StringBuffer target) { Map attributes = new SVNHashMap(); attributes.put("side", name); if (version.getRepositoryRoot() != null) { attributes.put("repos-url", version.getRepositoryRoot().toString()); } if (version.getPath() != null) { attributes.put("path-in-repos", version.getPath()); } if (version.getPegRevision() >= 0) { attributes.put("revision", Long.toString(version.getPegRevision())); } if (version.getKind() != SVNNodeKind.UNKNOWN) { attributes.put("kind", version.getKind().toString()); } return openXMLTag("version", SVNXMLUtil.XML_STYLE_SELF_CLOSING, attributes, target); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNListCommand.java000066400000000000000000000221351177510526000311330ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.ISVNDirEntryHandler; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNLogClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNListCommand extends SVNXMLCommand implements ISVNDirEntryHandler { public SVNListCommand() { super("list", new String[] {"ls"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.VERBOSE); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.INCREMENTAL); options.add(SVNOption.XML); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(null, true); if (targets.isEmpty()) { targets.add(""); } if (getSVNEnvironment().isXML()) { if (getSVNEnvironment().isVerbose()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'verbose' option invalid in XML mode"), SVNLogType.CLIENT); } if (!getSVNEnvironment().isIncremental()) { printXMLHeader("lists"); } } else if (getSVNEnvironment().isIncremental()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'incremental' option only valid in XML mode"), SVNLogType.CLIENT); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.IMMEDIATES; } int fields = getSVNEnvironment().isXML() || getSVNEnvironment().isVerbose() ? SVNDirEntry.DIRENT_ALL : SVNDirEntry.DIRENT_KIND | SVNDirEntry.DIRENT_TIME; boolean fetchLocks = getSVNEnvironment().isXML() || getSVNEnvironment().isVerbose(); SVNLogClient client = getSVNEnvironment().getClientManager().getLogClient(); boolean seenNonExistentPaths = false; for (int i = 0; i < targets.size(); i++) { String targetName = (String) targets.get(i); SVNPath target = new SVNPath(targetName, true); if (getSVNEnvironment().isXML()) { StringBuffer buffer = openXMLTag("list", SVNXMLUtil.XML_STYLE_NORMAL, "path", "".equals(target.getTarget()) ? "." : target.getTarget(), new StringBuffer()); getSVNEnvironment().getOut().print(buffer.toString()); } try { if (!target.isURL()) { client.doList(target.getFile(), target.getPegRevision(), getSVNEnvironment().getStartRevision(), fetchLocks, depth, fields, this); } else { client.doList(target.getURL(), target.getPegRevision(), getSVNEnvironment().getStartRevision(), fetchLocks, depth, fields, this); } } catch (SVNException e) { getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.WC_PATH_NOT_FOUND, SVNErrorCode.FS_NOT_FOUND}, getSVNEnvironment().isQuiet()); seenNonExistentPaths = true; } if (getSVNEnvironment().isXML()) { StringBuffer buffer = closeXMLTag("list", new StringBuffer()); getSVNEnvironment().getOut().print(buffer.toString()); } } if (getSVNEnvironment().isXML() && !getSVNEnvironment().isIncremental()) { printXMLFooter("lists"); } if (seenNonExistentPaths) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not list all targets because some targets don't exist"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { if (getSVNEnvironment().isXML()) { printDirEntryXML(dirEntry); } else { printDirEntry(dirEntry); } } protected void printDirEntry(SVNDirEntry dirEntry) { String path = dirEntry.getRelativePath(); if ("".equals(path)) { if (getSVNEnvironment().isVerbose() && dirEntry.getKind() == SVNNodeKind.DIR) { path = "."; } else if (dirEntry.getKind() == SVNNodeKind.DIR) { return; } } StringBuffer buffer = new StringBuffer(); if (getSVNEnvironment().isVerbose()) { buffer.append(SVNFormatUtil.formatString(dirEntry.getRevision() + "", 7, false)); buffer.append(' '); String author = dirEntry.getAuthor() == null ? " ? " : dirEntry.getAuthor(); if (author.length() > 8) { author = author.substring(0, 8); } buffer.append(SVNFormatUtil.formatString(author, 8, true)); buffer.append(' '); buffer.append(dirEntry.getLock() != null ? 'O' : ' '); buffer.append(' '); buffer.append(SVNFormatUtil.formatString(dirEntry.getKind() == SVNNodeKind.DIR ? "" : dirEntry.getSize() + "", 10, false)); buffer.append(' '); // time now. Date d = dirEntry.getDate(); String timeStr = ""; if (d != null) { if (System.currentTimeMillis() - d.getTime() < 365 * 1000 * 86400 / 2) { timeStr = SVNDate.formatConsoleShortDate(d); } else { timeStr = SVNDate.formatConsoleLongDate(d); } } buffer.append(SVNFormatUtil.formatString(timeStr, 12, false)); buffer.append(' '); } buffer.append(path); if (dirEntry.getKind() == SVNNodeKind.DIR) { buffer.append('/'); } buffer.append('\n'); getSVNEnvironment().getOut().print(buffer.toString()); } protected void printDirEntryXML(SVNDirEntry dirEntry) { String path = dirEntry.getRelativePath(); if ("".equals(path)) { if (getSVNEnvironment().isVerbose() && dirEntry.getKind() == SVNNodeKind.DIR) { path = "."; } else if (dirEntry.getKind() == SVNNodeKind.DIR) { return; } } StringBuffer buffer = new StringBuffer(); buffer = openXMLTag("entry", SVNXMLUtil.XML_STYLE_NORMAL, "kind", dirEntry.getKind().toString(), buffer); buffer = openCDataTag("name", path, buffer); if (dirEntry.getKind() == SVNNodeKind.FILE) { buffer = openCDataTag("size", Long.toString(dirEntry.getSize()), buffer); } buffer = openXMLTag("commit", SVNXMLUtil.XML_STYLE_NORMAL, "revision", Long.toString(dirEntry.getRevision()), buffer); buffer = openCDataTag("author", dirEntry.getAuthor(), buffer); if (dirEntry.getDate() != null) { buffer = openCDataTag("date", ((SVNDate) dirEntry.getDate()).format(), buffer); } buffer = closeXMLTag("commit", buffer); SVNLock lock = dirEntry.getLock(); if (lock != null) { buffer = openXMLTag("lock", SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); buffer = openCDataTag("token", lock.getID(), buffer); buffer = openCDataTag("owner", lock.getOwner(), buffer); buffer = openCDataTag("comment", lock.getComment(), buffer); buffer = openCDataTag("created", ((SVNDate) lock.getCreationDate()).format(), buffer); if (lock.getExpirationDate() != null && lock.getExpirationDate().getTime() > 0) { buffer = openCDataTag("expires", ((SVNDate) lock.getExpirationDate()).format(), buffer); } buffer = closeXMLTag("lock", buffer); } buffer = closeXMLTag("entry", buffer); getSVNEnvironment().getOut().print(buffer.toString()); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNLockCommand.java000066400000000000000000000117661177510526000311200ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLockCommand extends SVNCommand { public SVNLockCommand() { super("lock", null); } public boolean isCommitter() { return true; } public String getFileAmbigousErrorMessage() { return "Lock comment file is a versioned file; use '--force-log' to override"; } public String getMessageAmbigousErrorMessage() { return "The lock comment is a pathname (was -F intended?); use '--force-log' to override"; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.TARGETS); options.add(SVNOption.MESSAGE); options.add(SVNOption.FILE); options.add(SVNOption.FORCE_LOG); options.add(SVNOption.ENCODING); options.add(SVNOption.FORCE); return options; } public void run() throws SVNException { Collection targets = new ArrayList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); String message = getLockMessage(); Collection paths = new ArrayList(); Collection urls = new ArrayList(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isURL()) { urls.add(target.getURL()); } else { paths.add(target.getFile()); } } if (!paths.isEmpty()) { File[] filesArray = (File[]) paths.toArray(new File[paths.size()]); try { client.doLock(filesArray, getSVNEnvironment().isForce(), message); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_PATH_NOT_FOUND) { if (e.getErrorMessage().getRelatedObjects() != null && e.getErrorMessage().getRelatedObjects().length > 0 && e.getErrorMessage().getRelatedObjects()[0] instanceof File) { e.getErrorMessage().getRelatedObjects()[0] = ((File) e.getErrorMessage().getRelatedObjects()[0]).getAbsolutePath(); } } throw e; } } if (!urls.isEmpty()) { SVNURL[] urlsArray = (SVNURL[]) urls.toArray(new SVNURL[urls.size()]); client.doLock(urlsArray, getSVNEnvironment().isForce(), message); } } protected String getLockMessage() throws SVNException { if (getSVNEnvironment().getFileData() != null) { byte[] data = getSVNEnvironment().getFileData(); for (int i = 0; i < data.length; i++) { if (data[i] == 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_BAD_LOG_MESSAGE, "Log message contains a zero byte"), SVNLogType.CLIENT); } } try { return new String(getSVNEnvironment().getFileData(), getSVNEnvironment().getEncoding() != null ? getSVNEnvironment().getEncoding() : "UTF-8"); } catch (UnsupportedEncodingException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()), SVNLogType.CLIENT); } } else if (getSVNEnvironment().getMessage() != null) { return getSVNEnvironment().getMessage(); } return null; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNLogCommand.java000066400000000000000000000614021177510526000307410ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.PatternSyntaxException; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.SVNLogEntryPath; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.ISVNDiffGenerator; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.core.wc.SVNLogClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNRevisionRange; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLogCommand extends SVNXMLCommand implements ISVNLogEntryHandler { private static final String SEPARATOR = "------------------------------------------------------------------------\n"; private LinkedList myMergeStack; private String myAuthorOfInterest; private String myLogRegularExpression; private SVNPath myTarget; private SVNDepth myDepth; public SVNLogCommand() { super("log", null); } public boolean acceptsRevisionRange() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.DIFF); options.add(SVNOption.QUIET); options.add(SVNOption.VERBOSE); options.add(SVNOption.USE_MERGE_HISTORY); options.add(SVNOption.CHANGE); options.add(SVNOption.TARGETS); options.add(SVNOption.STOP_ON_COPY); options.add(SVNOption.INCREMENTAL); options.add(SVNOption.XML); options.add(SVNOption.LIMIT); options.add(SVNOption.WITH_ALL_REVPROPS); options.add(SVNOption.WITH_NO_REVPROPS); options.add(SVNOption.WITH_REVPROP); options.add(SVNOption.AUTHOR_OF_INTEREST); options.add(SVNOption.REGULAR_EXPRESSION); return options; } public void run() throws SVNException { if (!getSVNEnvironment().isXML()) { if (getSVNEnvironment().isAllRevisionProperties()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'with-all-revprops' option only valid in XML mode"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (getSVNEnvironment().getRevisionProperties() != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'with-revprop' option only valid in XML mode"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else { if (getSVNEnvironment().isShowDiff()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'diff' option is not supported in XML mode"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } if (getSVNEnvironment().isQuiet() && getSVNEnvironment().isShowDiff()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'quiet' and 'diff' options are mutually exclusive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (getSVNEnvironment().getDiffCommand() != null && !getSVNEnvironment().isShowDiff()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'diff-cmd' option requires 'diff' option"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (getSVNEnvironment().getExtensions() != null && !getSVNEnvironment().isShowDiff()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'extensions' option requires 'diff' option"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (getSVNEnvironment().getDepth() != SVNDepth.UNKNOWN && !getSVNEnvironment().isShowDiff()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'depth' option requires 'diff' option"); SVNErrorManager.error(err, SVNLogType.CLIENT); } List targets = new ArrayList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { targets.add(""); } SVNPath target = new SVNPath((String) targets.get(0), true); SVNRevision start = getSVNEnvironment().getStartRevision(); SVNRevision end = getSVNEnvironment().getEndRevision(); List revisionRanges = getSVNEnvironment().getRevisionRanges(); List editedRevisionRangesList = revisionRanges; if (getSVNEnvironment().isChangeOptionUsed()) { editedRevisionRangesList = new LinkedList(); if (getSVNEnvironment().isRevisionOptionUsed() && revisionRanges.size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "-c and -r are mutually exclusive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } for (Iterator revisionsIter = revisionRanges.iterator(); revisionsIter.hasNext();) { SVNRevisionRange revRange = (SVNRevisionRange) revisionsIter.next(); SVNRevision startRev = revRange.getStartRevision(); SVNRevision endRev = revRange.getEndRevision(); if (startRev.getNumber() < endRev.getNumber() && startRev.getNumber() >= 0 && endRev.getNumber() >= 0) { revRange = new SVNRevisionRange(SVNRevision.create(startRev.getNumber() + 1), endRev); } else { revRange = new SVNRevisionRange(startRev, SVNRevision.create(endRev.getNumber() + 1)); } editedRevisionRangesList.add(revRange); } if (start.getNumber() < end.getNumber()) { start = end; } else { end = start; } } if (start != SVNRevision.UNDEFINED && end == SVNRevision.UNDEFINED) { end = start; } else if (start == SVNRevision.UNDEFINED) { if (target.getPegRevision() == SVNRevision.UNDEFINED) { start = target.isURL() ? SVNRevision.HEAD : SVNRevision.BASE; } else { start = target.getPegRevision(); } if (end == SVNRevision.UNDEFINED) { end = SVNRevision.create(0); } } if (target.isURL()) { for(int i = 1; i < targets.size(); i++) { if (SVNCommandUtil.isURL((String) targets.get(i))) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Only relative paths can be specified after a URL"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } else { if (targets.size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "When specifying working copy paths, only one target may be given"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } myAuthorOfInterest = getSVNEnvironment().getAuthorOfInterest(); myLogRegularExpression = getSVNEnvironment().getRegularExpression(); myDepth = getSVNEnvironment().getDepth() == SVNDepth.UNKNOWN ? SVNDepth.INFINITY : getSVNEnvironment().getDepth(); myTarget = new SVNPath(target.getTarget(), target.getPegRevision() == SVNRevision.UNDEFINED ? (target.isURL() ? SVNRevision.HEAD : SVNRevision.WORKING) : target.getPegRevision()); SVNLogClient client = getSVNEnvironment().getClientManager().getLogClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } String[] revProps = null; if (getSVNEnvironment().isXML()) { if (!getSVNEnvironment().isIncremental()) { printXMLHeader("log"); } if (!getSVNEnvironment().isAllRevisionProperties() && getSVNEnvironment().getRevisionProperties() != null && !getSVNEnvironment().getRevisionProperties().isEmpty()) { SVNProperties revPropNames = getSVNEnvironment().getRevisionProperties(); revProps = new String[revPropNames.size()]; int i = 0; for (Iterator propNames = revPropNames.nameSet().iterator(); propNames.hasNext();) { String propName = (String) propNames.next(); String propVal = revPropNames.getStringValue(propName); if (propVal.length() > 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "cannot assign with 'with-revprop' option (drop the '=')"); SVNErrorManager.error(err, SVNLogType.CLIENT); } revProps[i++] = propName; } } else if (!getSVNEnvironment().isAllRevisionProperties()) { if (!getSVNEnvironment().isQuiet()) { revProps = new String[3]; revProps[0] = SVNRevisionProperty.AUTHOR; revProps[1] = SVNRevisionProperty.DATE; revProps[2] = SVNRevisionProperty.LOG; } else { revProps = new String[2]; revProps[0] = SVNRevisionProperty.AUTHOR; revProps[1] = SVNRevisionProperty.DATE; } } } else { if (!getSVNEnvironment().isQuiet()) { revProps = new String[3]; revProps[0] = SVNRevisionProperty.AUTHOR; revProps[1] = SVNRevisionProperty.DATE; revProps[2] = SVNRevisionProperty.LOG; } else { revProps = new String[2]; revProps[0] = SVNRevisionProperty.AUTHOR; revProps[1] = SVNRevisionProperty.DATE; } } if (target.isFile()) { client.doLog(new File[] {target.getFile()}, editedRevisionRangesList, target.getPegRevision(), getSVNEnvironment().isStopOnCopy(), getSVNEnvironment().isVerbose(), getSVNEnvironment().isUseMergeHistory(), getSVNEnvironment().getLimit(), revProps, this); } else { targets.remove(0); String[] paths = (String[]) targets.toArray(new String[targets.size()]); client.doLog(target.getURL(), paths, target.getPegRevision(), editedRevisionRangesList, getSVNEnvironment().isStopOnCopy(), getSVNEnvironment().isVerbose(), getSVNEnvironment().isUseMergeHistory(), getSVNEnvironment().getLimit(), revProps, this); } if (getSVNEnvironment().isXML() && !getSVNEnvironment().isIncremental()) { printXMLFooter("log"); } else if (!getSVNEnvironment().isIncremental()) { getSVNEnvironment().getOut().print(SEPARATOR); } } public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { if (!getSVNEnvironment().isXML()) { printLogEntry(logEntry); } else { printLogEntryXML(logEntry); } } protected void printLogEntry(SVNLogEntry logEntry) throws SVNException { if (logEntry == null) { return; } if (myAuthorOfInterest != null && !"".equals(myAuthorOfInterest) && !myAuthorOfInterest.equals(logEntry.getAuthor())) { return; } SVNProperties revisionProperties = logEntry.getRevisionProperties(); String author = revisionProperties.getStringValue(SVNRevisionProperty.AUTHOR); String message = revisionProperties.getStringValue(SVNRevisionProperty.LOG); String dateValue = revisionProperties.getStringValue(SVNRevisionProperty.DATE); Date dateObject = dateValue == null ? null : SVNDate.parseDate(dateValue); if (message == null && logEntry.getRevision() == 0) { return; } if (!SVNRevision.isValidRevisionNumber(logEntry.getRevision())) { if (!myMergeStack.isEmpty()) { myMergeStack.removeLast(); } return; } if (myLogRegularExpression != null) { if (message == null) { return; } String[] result = null; try { result = message.split(myLogRegularExpression); } catch (PatternSyntaxException psy) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "you specified an invalid regular expression: {0}", psy.getMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (result.length == 1 && message.equals(result[0]) && !message.equals(myLogRegularExpression)) { return; } } StringBuffer buffer = new StringBuffer(); if (author == null) { author = "(no author)"; } String date = dateObject == null ? "(no date)" : SVNDate.formatHumanDate(dateObject, getSVNEnvironment().getClientManager().getOptions()); if (!getSVNEnvironment().isQuiet() && message == null) { message = ""; } buffer.append(SEPARATOR); buffer.append("r" + Long.toString(logEntry.getRevision()) + " | " + author + " | " + date); if (message != null) { int count = SVNCommandUtil.getLinesCount(message); buffer.append(" | " + count + (count == 1 ? " line" : " lines")); } buffer.append("\n"); if (getSVNEnvironment().isVerbose() && logEntry.getChangedPaths() != null) { Map sortedPaths = new TreeMap(logEntry.getChangedPaths()); buffer.append("Changed paths:\n"); for (Iterator paths = sortedPaths.keySet().iterator(); paths.hasNext();) { String path = (String) paths.next(); SVNLogEntryPath lPath = (SVNLogEntryPath) sortedPaths.get(path); buffer.append(" " + lPath.getType() + " " + path); if (lPath.getCopyPath() != null) { buffer.append(" (from " + lPath.getCopyPath() + ":" + lPath.getCopyRevision() + ")"); } buffer.append("\n"); } } if (myMergeStack != null && !myMergeStack.isEmpty()) { buffer.append(logEntry.isSubtractiveMerge() ? "Reverse merged via:" : "Merged via:"); for (Iterator revs = myMergeStack.iterator(); revs.hasNext();) { long rev = ((Long) revs.next()).longValue(); buffer.append(" r"); buffer.append(rev); if (revs.hasNext()) { buffer.append(','); } else { buffer.append('\n'); } } } if (message != null) { buffer.append("\n" + message + "\n"); } if (logEntry.hasChildren()) { Long rev = new Long(logEntry.getRevision()); if (myMergeStack == null) { myMergeStack = new LinkedList(); } myMergeStack.addLast(rev); } getSVNEnvironment().getOut().print(buffer.toString()); if (getSVNEnvironment().isShowDiff()) { getSVNEnvironment().getOut().println(); SVNClientManager diffClientManager = getEnvironment().createClientManager(); try { //TODO: parse diff options here SVNDiffClient client = diffClientManager.getDiffClient(); client.setShowCopiesAsAdds(false); final ISVNDiffGenerator diffGenerator = SVNDiffCommand.createDiffGenerator(getSVNEnvironment()); diffGenerator.setDiffDeleted(false); client.setDiffGenerator(diffGenerator); try { doDiff(client, logEntry, myTarget, myDepth); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NOT_FOUND) { SVNPath parent = getParentPath(myTarget); while (!myTarget.equals(parent)) { try { doDiff(client, logEntry, parent, myDepth); } catch (SVNException e1) { if (e1.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NOT_FOUND) { parent = getParentPath(parent); } else if (e1.getErrorMessage().getErrorCode() == SVNErrorCode.RA_ILLEGAL_URL || e1.getErrorMessage().getErrorCode() == SVNErrorCode.AUTHZ_UNREADABLE || e1.getErrorMessage().getErrorCode() == SVNErrorCode.RA_LOCAL_REPOS_OPEN_FAILED) { break; } else { throw e1; } } break; } } else { throw e; } } } finally { diffClientManager.dispose(); } getSVNEnvironment().getOut().println(); } } private SVNPath getParentPath(SVNPath target) { return new SVNPath(SVNPathUtil.removeTail(target.getTarget()), target.getPegRevision()); } private void doDiff(SVNDiffClient client, SVNLogEntry logEntry, SVNPath target, SVNDepth depth) throws SVNException { if (target.isFile()) { client.doDiff(target.getFile(), target.getPegRevision(), SVNRevision.create(logEntry.getRevision() - 1), SVNRevision.create(logEntry.getRevision()), depth, true, getSVNEnvironment().getOut(), getSVNEnvironment().getChangelistsCollection()); } else { client.doDiff(target.getURL(), target.getPegRevision(), SVNRevision.create(logEntry.getRevision() - 1), SVNRevision.create(logEntry.getRevision()), depth, true, getSVNEnvironment().getOut()); } } protected void printLogEntryXML(SVNLogEntry logEntry) throws SVNException { if (logEntry == null) { return; } if (myAuthorOfInterest != null && !"".equals(myAuthorOfInterest) && !myAuthorOfInterest.equals(logEntry.getAuthor())) { return; } SVNProperties revProps = logEntry.getRevisionProperties(); String author = revProps.getStringValue(SVNRevisionProperty.AUTHOR); String message = revProps.getStringValue(SVNRevisionProperty.LOG); String dateValue = revProps.getStringValue(SVNRevisionProperty.DATE); Date dateObject = dateValue == null ? null : SVNDate.parseDate(dateValue); if (logEntry.getRevision() == 0 && message == null) { return; } if (myLogRegularExpression != null) { if (message == null) { return; } String[] result = null; try { result = message.split(myLogRegularExpression); } catch (PatternSyntaxException psy) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "you specified an invalid regular expression: {0}", psy.getMessage()); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (result.length == 1 && message.equals(result[0]) && !message.equals(myLogRegularExpression)) { return; } } if (author != null) { author = SVNEncodingUtil.fuzzyEscape(author); } if (message != null) { message = SVNEncodingUtil.fuzzyEscape(message); } StringBuffer buffer = new StringBuffer(); if (!SVNRevision.isValidRevisionNumber(logEntry.getRevision())) { buffer = closeXMLTag("logentry", null); getSVNEnvironment().getOut().print(buffer.toString()); if (!myMergeStack.isEmpty()) { myMergeStack.removeLast(); } return; } buffer = openXMLTag("logentry", SVNXMLUtil.XML_STYLE_NORMAL, "revision", Long.toString(logEntry.getRevision()), buffer); buffer = openCDataTag("author", author, buffer); if (dateObject != null && dateObject.getTime() != 0) { String dateString = SVNEncodingUtil.fuzzyEscape(((SVNDate) dateObject).format()); buffer = openCDataTag("date", dateString, buffer); } if (logEntry.getChangedPaths() != null && !logEntry.getChangedPaths().isEmpty()) { buffer = openXMLTag("paths", SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); for (Iterator paths = logEntry.getChangedPaths().keySet().iterator(); paths.hasNext();) { String key = (String) paths.next(); SVNLogEntryPath path = (SVNLogEntryPath) logEntry.getChangedPaths().get(key); Map attrs = new LinkedHashMap(); attrs.put("action", path.getType() + ""); if (path.getCopyPath() != null) { attrs.put("copyfrom-path", path.getCopyPath()); attrs.put("copyfrom-rev", Long.toString(path.getCopyRevision())); } buffer = openXMLTag("path", SVNXMLUtil.XML_STYLE_PROTECT_CDATA, attrs, buffer); buffer.append(SVNEncodingUtil.xmlEncodeCDATA(path.getPath())); buffer = closeXMLTag("path", buffer); } buffer = closeXMLTag("paths", buffer); } if (message != null) { buffer = openCDataTag("msg", message, buffer); } if (revProps != null) { revProps.remove(SVNRevisionProperty.AUTHOR); revProps.remove(SVNRevisionProperty.DATE); revProps.remove(SVNRevisionProperty.LOG); } if (revProps != null && !revProps.isEmpty()) { buffer = openXMLTag("revprops", SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); buffer = printXMLPropHash(buffer, revProps, false); buffer = closeXMLTag("revprops", buffer); } if (logEntry.hasChildren()) { if (myMergeStack == null) { myMergeStack = new LinkedList(); } myMergeStack.addLast(new Long(logEntry.getRevision())); } else { buffer = closeXMLTag("logentry", buffer); } getSVNEnvironment().getOut().print(buffer.toString()); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMergeCommand.java000066400000000000000000000321771177510526000312660ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNRevisionRange; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNMergeCommand extends SVNCommand { public SVNMergeCommand() { super("merge", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.CHANGE); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.QUIET); options.add(SVNOption.FORCE); options.add(SVNOption.DRY_RUN); options.add(SVNOption.DIFF3_CMD); options.add(SVNOption.RECORD_ONLY); options.add(SVNOption.EXTENSIONS); options.add(SVNOption.IGNORE_ANCESTRY); options.add(SVNOption.ACCEPT); options.add(SVNOption.REINTEGRATE); options.add(SVNOption.ALLOW_MIXED_REVISIONS); return options; } public boolean acceptsRevisionRange() { return true; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(new ArrayList(), true); SVNPath source1 = null; SVNPath source2 = null; SVNPath target = null; SVNRevision pegRevision1 = null; SVNRevision pegRevision2 = null; if (targets.size() >= 1) { source1 = new SVNPath((String) targets.get(0), true); pegRevision1 = source1.getPegRevision(); if (targets.size() >= 2) { source2 = new SVNPath((String) targets.get(1), true); pegRevision2 = source2.getPegRevision(); } } boolean twoSourcesSpecified = true; if (targets.size() <= 1) { twoSourcesSpecified = false; } else if (targets.size() == 2) { if (source1.isURL() && !source2.isURL()) { twoSourcesSpecified = false; } } List rangesToMerge = getSVNEnvironment().getRevisionRanges(); SVNRevision firstRangeStart = SVNRevision.UNDEFINED; SVNRevision firstRangeEnd = SVNRevision.UNDEFINED; if (!rangesToMerge.isEmpty()) { SVNRevisionRange range = (SVNRevisionRange) rangesToMerge.get(0); firstRangeStart = range.getStartRevision(); firstRangeEnd = range.getEndRevision(); } if (firstRangeStart != SVNRevision.UNDEFINED) { if (firstRangeEnd == SVNRevision.UNDEFINED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Second revision required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } twoSourcesSpecified = false; } if (!twoSourcesSpecified) { if (targets.size() > 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Too many arguments given"), SVNLogType.CLIENT); } if (targets.isEmpty()) { pegRevision1 = SVNRevision.HEAD; } else { source2 = source1; if (pegRevision1 == null || pegRevision1 == SVNRevision.UNDEFINED) { pegRevision1 = source1.isURL() ? SVNRevision.HEAD : SVNRevision.WORKING; } if (targets.size() == 2) { target = new SVNPath((String) targets.get(1)); if (target.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Cannot specifify a revision range with two URLs"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } } else { if (targets.size() < 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } else if (targets.size() > 3) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Too many arguments given"), SVNLogType.CLIENT); } firstRangeStart = pegRevision1; firstRangeEnd = pegRevision2; if (((firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) && !source1.isURL()) || ((pegRevision2 == null || pegRevision2 == SVNRevision.UNDEFINED) && !source2.isURL())) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "A working copy merge source needs an explicit revision"), SVNLogType.CLIENT); } if (firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) { firstRangeStart = SVNRevision.HEAD; } if (firstRangeEnd == null || firstRangeEnd == SVNRevision.UNDEFINED) { firstRangeEnd = SVNRevision.HEAD; } if (targets.size() >= 3) { target = new SVNPath((String) targets.get(2)); } } if (source1 != null && source2 != null && target == null) { if (source1.isURL()) { String name1 = SVNPathUtil.tail(source1.getTarget()); String name2 = SVNPathUtil.tail(source2.getTarget()); if (name1.equals(name2)) { String decodedPath = SVNEncodingUtil.uriDecode(name1); SVNPath decodedPathTarget = new SVNPath(decodedPath); if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) { target = decodedPathTarget; } } } else if (source1.equals(source2)) { String decodedPath = SVNEncodingUtil.uriDecode(source1.getTarget()); SVNPath decodedPathTarget = new SVNPath(decodedPath); if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) { target = decodedPathTarget; } } } if (target == null) { target = new SVNPath(""); } SVNDiffClient client = getSVNEnvironment().getClientManager().getDiffClient(); SVNNotifyPrinter printer = new SVNNotifyPrinter(getSVNEnvironment()); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(printer); } client.setAllowMixedRevisionsWCForMerge(getSVNEnvironment().isAllowMixedRevisions()); try { client.setMergeOptions(getSVNEnvironment().getDiffOptions()); try { if (!twoSourcesSpecified) { if (firstRangeStart == SVNRevision.UNDEFINED && firstRangeEnd == SVNRevision.UNDEFINED) { SVNRevisionRange range = new SVNRevisionRange(SVNRevision.create(1), pegRevision1); rangesToMerge = new LinkedList(); rangesToMerge.add(range); } if (source1 == null) { source1 = target; } if (getSVNEnvironment().isReIntegrate()) { if (getSVNEnvironment().getDepth() != SVNDepth.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--depth cannot be used with --reintegrate"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (getSVNEnvironment().isForce()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--force cannot be used with --reintegrate"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (source1.isURL()) { client.doMergeReIntegrate(source1.getURL(), pegRevision1, target.getFile(), getSVNEnvironment().isDryRun()); } else { client.doMergeReIntegrate(source1.getFile(), pegRevision1, target.getFile(), getSVNEnvironment().isDryRun()); } } else { if (source1.isURL()) { client.doMerge(source1.getURL(), pegRevision1, rangesToMerge, target.getFile(), getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly()); } else { client.doMerge(source1.getFile(), pegRevision1, rangesToMerge, target.getFile(), getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly()); } } } else { if (source1.isURL() && source2.isURL()) { client.doMerge(source1.getURL(), firstRangeStart, source2.getURL(), firstRangeEnd, target.getFile(), getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly()); } else if (source1.isURL() && source2.isFile()) { client.doMerge(source1.getURL(), firstRangeStart, source2.getFile(), firstRangeEnd, target.getFile(), getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly()); } else if (source1.isFile() && source2.isURL()) { client.doMerge(source1.getFile(), firstRangeStart, source2.getURL(), firstRangeEnd, target.getFile(), getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly()); } else { client.doMerge(source1.getFile(), firstRangeStart, source2.getFile(), firstRangeEnd, target.getFile(), getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly()); } } } finally { if (!getSVNEnvironment().isQuiet()) { StringBuffer status = new StringBuffer(); printer.printConflictStatus(status); getSVNEnvironment().getOut().print(status); } } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (err != null && !getSVNEnvironment().isReIntegrate()) { SVNErrorCode code = err.getErrorCode(); if (code == SVNErrorCode.UNVERSIONED_RESOURCE || code == SVNErrorCode.CLIENT_MODIFIED) { err = err.wrap("Use --force to override this restriction"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } throw e; } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMergeInfoCommand.java000066400000000000000000000122151177510526000320710ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.text.MessageFormat; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.ISvnObjectReceiver; import org.tmatesoft.svn.core.wc2.SvnLogMergeInfo; import org.tmatesoft.svn.core.wc2.SvnOperationFactory; import org.tmatesoft.svn.core.wc2.SvnTarget; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNMergeInfoCommand extends SVNCommand implements ISVNLogEntryHandler { public SVNMergeInfoCommand() { super("mergeinfo", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.SHOW_REVS); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(null, true); if (targets.size() < 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Not enough arguments given"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (targets.size() > 2) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Too many arguments given"); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPath source = new SVNPath((String) targets.get(0), true); SVNRevision srcPegRevision = source.getPegRevision(); if (srcPegRevision == SVNRevision.UNDEFINED) { srcPegRevision = SVNRevision.HEAD; } SVNPath target = null; SVNRevision tgtPegRevision = null; if (targets.size() == 2) { target = new SVNPath((String) targets.get(1), true); tgtPegRevision = target.getPegRevision(); } else { target = new SVNPath(""); tgtPegRevision = SVNRevision.UNDEFINED; } if (tgtPegRevision == SVNRevision.UNDEFINED) { if (target.isURL()) { tgtPegRevision = SVNRevision.HEAD; } else { tgtPegRevision = SVNRevision.BASE; } } SVNDiffClient client = getSVNEnvironment().getClientManager().getDiffClient(); SvnOperationFactory of = client.getOperationsFactory(); SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } SvnLogMergeInfo logMergeInfo = of.createLogMergeInfo(); logMergeInfo.setDepth(depth); logMergeInfo.setDiscoverChangedPaths(true); logMergeInfo.setRevisionProperties(null); logMergeInfo.setReceiver(new ISvnObjectReceiver() { public void receive(SvnTarget target, SVNLogEntry object) throws SVNException { handleLogEntry(object); } }); logMergeInfo.setFindMerged(getSVNEnvironment().getShowRevisionType() == SVNShowRevisionType.MERGED); if (target.isURL()) { logMergeInfo.setSingleTarget(SvnTarget.fromURL(target.getURL(), tgtPegRevision)); } else { logMergeInfo.setSingleTarget(SvnTarget.fromFile(target.getFile(), tgtPegRevision)); } if (source.isURL()) { logMergeInfo.setSource(SvnTarget.fromURL(source.getURL(), srcPegRevision)); } else { logMergeInfo.setSource(SvnTarget.fromFile(source.getFile(), srcPegRevision)); } logMergeInfo.run(); } public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { String message; if (logEntry.isNonInheritable()) { message = MessageFormat.format("r{0}*", new Object[] { String.valueOf(logEntry.getRevision()) }); } else { message = MessageFormat.format("r{0}", new Object[] { String.valueOf(logEntry.getRevision()) }); } getSVNEnvironment().getOut().println(message); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMkDirCommand.java000066400000000000000000000135531177510526000312320ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNCommitClient; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNMkDirCommand extends SVNCommand { public SVNMkDirCommand() { super("mkdir", null); } public boolean isCommitter() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.QUIET); options.add(SVNOption.PARENTS); options = SVNOption.addLogMessageOptions(options); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } boolean hasURLs = false; boolean hasPaths = false; for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); if (!SVNCommandUtil.isURL(targetName)) { hasPaths = true; } else { hasURLs = true; } } if (hasURLs && hasPaths) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Cannot mix repository and working copy targets"), SVNLogType.CLIENT); } if (hasPaths && (getSVNEnvironment().getMessage() != null || getSVNEnvironment().getFileData() != null || getSVNEnvironment().getRevisionProperties() != null)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_UNNECESSARY_LOG_MESSAGE, "Local, non-commit operations do not take a log message or revision properties"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (hasURLs) { SVNCommitClient client = getSVNEnvironment().getClientManager().getCommitClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } client.setCommitHandler(getSVNEnvironment()); SVNURL[] urls = new SVNURL[targets.size()]; for (int i = 0; i < targets.size(); i++) { String url = (String) targets.get(i); urls[i] = SVNURL.parseURIEncoded(url); } try { SVNCommitInfo info = client.doMkDir(urls, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().isParents()); if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().printCommitInfo(info); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (!getSVNEnvironment().isParents() && (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.FS_NOT_DIRECTORY || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND)) { err = err.wrap("Try 'svn mkdir --parents' instead?"); } SVNErrorManager.error(err, SVNLogType.CLIENT); } } else { SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } try { for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); client.doAdd(target.getFile(), false, true, false, SVNDepth.INFINITY, false, getSVNEnvironment().isParents()); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.IO_ERROR) { err = err.wrap("Try 'svn add' or 'svn add --non-recursive' instead?"); } else if (!getSVNEnvironment().isParents() && (err.getErrorCode() == SVNErrorCode.IO_ERROR || err.getErrorCode() == SVNErrorCode.WC_PATH_NOT_FOUND || err.getErrorCode() == SVNErrorCode.FS_NOT_DIRECTORY || err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.ENTRY_NOT_FOUND )) { err = err.wrap("Try 'svn mkdir --parents' instead?"); } SVNErrorManager.error(err, SVNLogType.CLIENT); } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMoveCommand.java000066400000000000000000000113161177510526000311250ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNCopyClient; import org.tmatesoft.svn.core.wc.SVNCopySource; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNMoveCommand extends SVNCommand { public SVNMoveCommand() { super("move", new String[] {"mv", "rename", "ren"}); } public boolean isCommitter() { return true; } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.QUIET); options.add(SVNOption.FORCE); options.add(SVNOption.PARENTS); options = SVNOption.addLogMessageOptions(options); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(null, true); if (targets.size() < 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } if (getSVNEnvironment().getStartRevision() != SVNRevision.UNDEFINED && getSVNEnvironment().getStartRevision() != SVNRevision.HEAD) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot specify revision (except HEAD) with move operation"), SVNLogType.CLIENT); } SVNPath dst = new SVNPath((String) targets.remove(targets.size() - 1)); if (!dst.isURL()) { if (getSVNEnvironment().getMessage() != null || getSVNEnvironment().getFileData() != null || getSVNEnvironment().getRevisionProperties() != null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_UNNECESSARY_LOG_MESSAGE, "Local, non-commit operations do not take a log message or revision properties"), SVNLogType.CLIENT); } } SVNCopyClient client = getSVNEnvironment().getClientManager().getCopyClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } client.setCommitHandler(getSVNEnvironment()); Collection sources = new ArrayList(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath source = new SVNPath(targetName); if (source.isURL()) { sources.add(new SVNCopySource(SVNRevision.HEAD, SVNRevision.UNDEFINED, source.getURL())); } else { sources.add(new SVNCopySource(getSVNEnvironment().getStartRevision(), SVNRevision.UNDEFINED, source.getFile())); } } SVNCopySource[] copySources = (SVNCopySource[]) sources.toArray(new SVNCopySource[sources.size()]); try { if (dst.isURL()) { SVNCommitInfo info = client.doCopy(copySources, dst.getURL(), true, getSVNEnvironment().isParents(), false, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties()); if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().printCommitInfo(info); } } else { client.doCopy(copySources, dst.getFile(), true, getSVNEnvironment().isParents(), false); } } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); SVNErrorCode code = err.getErrorCode(); if (code == SVNErrorCode.UNVERSIONED_RESOURCE || code == SVNErrorCode.CLIENT_MODIFIED) { err = err.wrap("Use --force to override this restriction"); } SVNErrorManager.error(err, e, SVNLogType.CLIENT); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNNotifyPrinter.java000066400000000000000000000577541177510526000315540ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.*; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.wc.patch.SVNPatchHunk; import org.tmatesoft.svn.core.internal.wc.patch.SVNPatchHunkInfo; import org.tmatesoft.svn.core.wc.*; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; import java.io.File; import java.io.PrintStream; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNNotifyPrinter implements ISVNEventHandler { private SVNCommandEnvironment myEnvironment; private boolean myIsInExternal; private boolean myIsChangesReceived; private boolean myIsDeltaSent; private boolean myIsCheckout; private boolean myIsExport; private boolean myIsSuppressLastLine; private int myTextConflicts = 0; private int myPropConflicts = 0; private int myTreeConflicts = 0; private int mySkippedPaths = 0; private boolean myHasExternalErrors; private boolean myHasLockingError; private boolean myIsWcToReposCopy; public SVNNotifyPrinter(SVNCommandEnvironment env) { this(env, false, false, false); } public SVNNotifyPrinter(SVNCommandEnvironment env, boolean isCheckout, boolean isExport, boolean suppressLastLine) { myEnvironment = env; myIsCheckout = isCheckout; myIsExport = isExport; myIsSuppressLastLine = suppressLastLine; } public void setWcToReposCopy(boolean wcToReposCopy) { myIsWcToReposCopy = wcToReposCopy; } public boolean isWcToReposCopy() { return myIsWcToReposCopy; } public boolean hasExternalErrors() { return myHasExternalErrors; } public boolean hasLockingErrors() { return myHasLockingError; } public void handleEvent(SVNEvent event, double progress) throws SVNException { File file = event.getFile(); String path = null; if (file != null) { path = myEnvironment.getRelativePath(file); path = SVNCommandUtil.getLocalPath(path); } PrintStream out = myEnvironment.getOut(); StringBuffer buffer = new StringBuffer(); if (event.getAction() == SVNEventAction.STATUS_EXTERNAL) { buffer.append("\nPerforming status on external item at '" + path + "'\n"); } else if (event.getAction() == SVNEventAction.STATUS_COMPLETED) { if (SVNRevision.isValidRevisionNumber(event.getRevision())) { String revStr = Long.toString(event.getRevision()); buffer.append("Status against revision: " + SVNFormatUtil.formatString(revStr, 6, false) + "\n"); } } else if (event.getAction() == SVNEventAction.SKIP) { if (event.getErrorMessage() != null && event.getExpectedAction() == SVNEventAction.UPDATE_EXTERNAL) { // hack to let external test #14 work. myEnvironment.getErr().println(event.getErrorMessage()); } mySkippedPaths++; if (event.getContentsStatus() == SVNStatusType.MISSING) { buffer.append("Skipped missing target: '" + path + "'\n"); } else if (path != null) { buffer.append("Skipped '" + path + "'\n"); } } else if (event.getAction() == SVNEventAction.UPDATE_SKIP_OBSTRUCTION) { mySkippedPaths++; buffer.append("Skipped '" + path + "' -- An obstructing working copy was found\n"); } else if (event.getAction() == SVNEventAction.UPDATE_SKIP_WORKING_ONLY) { mySkippedPaths++; buffer.append("Skipped '" + path + "' -- Has no versioned parent\n"); } else if (event.getAction() == SVNEventAction.UPDATE_SKIP_ACCESS_DENINED) { mySkippedPaths++; buffer.append("Skipped '" + path + "' -- Access denied\n"); } else if (event.getAction() == SVNEventAction.SKIP_CONFLICTED) { mySkippedPaths++; buffer.append("Skipped '" + path + "' -- Node remains in conflict\n"); } else if (event.getAction() == SVNEventAction.UPDATE_DELETE) { myIsChangesReceived = true; buffer.append("D " + path + "\n"); } else if (event.getAction() == SVNEventAction.UPDATE_REPLACE) { myIsChangesReceived = true; buffer.append("R " + path + "\n"); } else if (event.getAction() == SVNEventAction.UPDATE_ADD) { myIsChangesReceived = true; if (event.getContentsStatus() == SVNStatusType.CONFLICTED) { myTextConflicts++; buffer.append("C " + path + "\n"); } else { buffer.append("A " + path + "\n"); } } else if (event.getAction() == SVNEventAction.UPDATE_EXISTS) { myIsChangesReceived = true; if (event.getContentsStatus() == SVNStatusType.CONFLICTED) { myTextConflicts++; buffer.append('C'); } else { buffer.append('E'); } if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) { myPropConflicts++; buffer.append('C'); } else if (event.getPropertiesStatus() == SVNStatusType.MERGED) { buffer.append('G'); } else { buffer.append(' '); } buffer.append(" " + path + "\n"); } else if (event.getAction() == SVNEventAction.UPDATE_UPDATE || event.getAction() == SVNEventAction.MERGE_RECORD_INFO) { SVNStatusType propStatus = event.getPropertiesStatus(); if (event.getNodeKind() == SVNNodeKind.DIR && (propStatus == SVNStatusType.INAPPLICABLE || propStatus == SVNStatusType.UNKNOWN || propStatus == SVNStatusType.UNCHANGED)) { return; } if (event.getNodeKind() == SVNNodeKind.FILE) { if (event.getContentsStatus() == SVNStatusType.CONFLICTED) { myTextConflicts++; buffer.append('C'); } else if (event.getContentsStatus() == SVNStatusType.MERGED){ buffer.append('G'); } else if (event.getContentsStatus() == SVNStatusType.CHANGED){ buffer.append('U'); } else { buffer.append(' '); } } else { buffer.append(' '); } if (event.getPropertiesStatus() == SVNStatusType.CONFLICTED) { myPropConflicts++; buffer.append('C'); } else if (event.getPropertiesStatus() == SVNStatusType.MERGED){ buffer.append('G'); } else if (event.getPropertiesStatus() == SVNStatusType.CHANGED){ buffer.append('U'); } else { buffer.append(' '); } if (buffer.toString().trim().length() > 0) { myIsChangesReceived = true; } if (event.getLockStatus() == SVNStatusType.LOCK_UNLOCKED) { buffer.append('B'); } else { buffer.append(' '); } if (buffer.toString().trim().length() == 0) { return; } buffer.append(" " + path + "\n"); } else if (event.getAction() == SVNEventAction.MERGE_BEGIN) { SVNMergeRange range = event.getMergeRange(); if (range == null) { buffer.append("--- Merging differences between repository URLs into '" + path + "':\n"); } else { long start = range.getStartRevision(); long end = range.getEndRevision(); if (start == end || start == end - 1) { buffer.append("--- Merging r" + end + " into '" + path + "':\n"); } else if (start - 1 == end) { buffer.append("--- Reverse-merging r" + start + " into '" + path + "':\n"); } else if (start < end) { buffer.append("--- Merging r" + (start + 1) + " through r" + end + " into '" + path + "':\n"); } else { buffer.append("--- Reverse-merging r" + start + " through r" + (end + 1) + " into '" + path + "':\n"); } } } else if (event.getAction() == SVNEventAction.MERGE_RECORD_INFO_BEGIN) { SVNMergeRange range = event.getMergeRange(); if (range == null) { buffer.append("--- Recording mergeinfo for merge between repository URLs into '" + path + "':\n"); } else { long start = range.getStartRevision(); long end = range.getEndRevision(); if (start == end || start == end - 1) { buffer.append("--- Recording mergeinfo for merge of r" + end + " into '" + path + "':\n"); } else if (start - 1 == end) { buffer.append("--- Recording mergeinfo for reverse merge of r" + start + " into '" + path + "':\n"); } else if (start < end) { buffer.append("--- Recording mergeinfo for merge of r" + (start + 1) + " through r" + end + " into '" + path + "':\n"); } else { buffer.append("--- Recording mergeinfo for reverse merge of r" + start + " through r" + (end + 1) + " into '" + path + "':\n"); } } } else if (event.getAction() == SVNEventAction.FOREIGN_MERGE_BEGIN) { SVNMergeRange range = event.getMergeRange(); if (range == null) { buffer.append("--- Merging differences between foreign repository URLs into '" + path + "':\n"); } else { long start = range.getStartRevision(); long end = range.getEndRevision(); if (start == end || start == end - 1) { buffer.append("--- Merging (from foreign repository) r" + end + " into '" + path + "':\n"); } else if (start - 1 == end) { buffer.append("--- Reverse-merging (from foreign repository) r" + start + " into '" + path + "':\n"); } else if (start < end) { buffer.append("--- Merging (from foreign repository) r" + (start + 1) + " through r" + end + " into '" + path + "':\n"); } else { buffer.append("--- Reverse-merging (from foreign repository) r" + start + " through r" + (end + 1) + " into '" + path + "':\n"); } } } else if (event.getAction() == SVNEventAction.MERGE_ELIDE_INFO) { buffer.append("--- Eliding mergeinfo from '" + path + "':\n"); } else if (event.getAction() == SVNEventAction.TREE_CONFLICT) { myTreeConflicts++; buffer.append(" C "); buffer.append(path); buffer.append("\n"); } else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_ADD) { myIsChangesReceived = true; buffer.append(" A "); buffer.append(path); buffer.append("\n"); } else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_UPDATE) { myIsChangesReceived = true; buffer.append(" U "); buffer.append(path); buffer.append("\n"); } else if (event.getAction() == SVNEventAction.UPDATE_SHADOWED_DELETE) { myIsChangesReceived = true; buffer.append(" D "); buffer.append(path); buffer.append("\n"); } else if (event.getAction() == SVNEventAction.RESTORE) { buffer.append("Restored '" + path + "'\n"); } else if (event.getAction() == SVNEventAction.RESTORE) { buffer.append("Restored '" + path + "'\n"); } else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL) { myIsInExternal = true; buffer.append("\nFetching external item into '" + path + "':\n"); } else if (event.getAction() == SVNEventAction.UPDATE_EXTERNAL_REMOVED) { buffer.append("Removed external '" + path + "'"); if (event.getErrorMessage() != null) { buffer.append(": " + event.getErrorMessage().getMessage()); } buffer.append("\n"); } else if (event.getAction() == SVNEventAction.FAILED_EXTERNAL) { myHasExternalErrors = true; if (myIsInExternal) { myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() }, myEnvironment.isQuiet()); myIsInExternal = false; return; } SVNErrorMessage warnMessage = SVNErrorMessage.create(SVNErrorCode.CL_ERROR_PROCESSING_EXTERNALS, "Error handling externals definition for ''{0}'':", path); myEnvironment.handleWarning(warnMessage, new SVNErrorCode[] { warnMessage.getErrorCode() }, myEnvironment.isQuiet()); myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() }, myEnvironment.isQuiet()); return; } else if(event.getAction() == SVNEventAction.UPDATE_STARTED) { if (! (myIsSuppressLastLine || myIsInExternal || myIsCheckout || myIsExport)) { buffer.append("Updating '"+path+"':\n"); } } else if (event.getAction() == SVNEventAction.UPDATE_COMPLETED) { if (!myIsSuppressLastLine) { long rev = event.getRevision(); if (rev >= 0) { if (myIsExport) { buffer.append(myIsInExternal ? "Exported external at revision " + rev + ".\n" : "Exported revision " + rev + ".\n"); } else if (myIsCheckout) { buffer.append(myIsInExternal ? "Checked out external at revision " + rev + ".\n" : "Checked out revision " + rev + ".\n"); } else { if (myIsChangesReceived) { buffer.append(myIsInExternal ? "Updated external to revision " + rev + ".\n" : "Updated to revision " + rev + ".\n"); } else { buffer.append(myIsInExternal ? "External at revision " + rev + ".\n" : "At revision " + rev + ".\n"); } } } else { if (myIsExport) { buffer.append(myIsInExternal ? "External export complete.\n" : "Export complete.\n"); } else if (myIsCheckout) { buffer.append(myIsInExternal ? "External checkout complete.\n" : "Checkout complete.\n"); } } } if (myIsInExternal) { buffer.append('\n'); myIsInExternal = false; } } else if (event.getAction() == SVNEventAction.COMMIT_MODIFIED) { buffer.append((!isWcToReposCopy() ? "Sending " : "Sending copy of ") + path + "\n"); } else if (event.getAction() == SVNEventAction.COMMIT_ADDED) { if (SVNProperty.isBinaryMimeType(event.getMimeType())) { buffer.append((!isWcToReposCopy() ? "Adding (bin) " : "Adding copy of (bin) ") + path + "\n"); } else { buffer.append((!isWcToReposCopy() ? "Adding " : "Adding copy of ") + path + "\n"); } } else if (event.getAction() == SVNEventAction.COMMIT_DELETED) { buffer.append((!isWcToReposCopy() ? "Deleting " : "Deleting copy of ") + path + "\n"); } else if (event.getAction() == SVNEventAction.COMMIT_REPLACED) { buffer.append((!isWcToReposCopy() ? "Replacing " : "Replacing copy of ") + path + "\n"); } else if (event.getAction() == SVNEventAction.COMMIT_DELTA_SENT) { if (!myIsDeltaSent) { myIsDeltaSent = true; buffer.append("Transmitting file data "); } buffer.append('.'); } else if (event.getAction() == SVNEventAction.ADD || event.getAction() == SVNEventAction.COPY) { if (SVNProperty.isBinaryMimeType(event.getMimeType())) { buffer.append("A (bin) " + path + "\n"); } else { buffer.append("A " + path + "\n"); } } else if (event.getAction() == SVNEventAction.DELETE) { buffer.append("D " + path + "\n"); } else if (event.getAction() == SVNEventAction.REVERT) { buffer.append("Reverted '" + path + "'\n"); } else if (event.getAction() == SVNEventAction.FAILED_REVERT) { buffer.append("Failed to revert '" + path + "' -- try updating instead.\n"); } else if (event.getAction() == SVNEventAction.LOCKED) { buffer.append("'" + path + "' locked by user '" + event.getLock().getOwner() + "'.\n"); } else if (event.getAction() == SVNEventAction.UNLOCKED) { buffer.append("'" + path + "' unlocked.\n"); } else if (event.getAction() == SVNEventAction.LOCK_FAILED || event.getAction() == SVNEventAction.UNLOCK_FAILED) { myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] {event.getErrorMessage().getErrorCode()}, myEnvironment.isQuiet()); myHasLockingError = true; return; } else if (event.getAction() == SVNEventAction.RESOLVED) { buffer.append("Resolved conflicted state of '" + path + "'\n"); } else if (event.getAction() == SVNEventAction.CHANGELIST_SET) { buffer.append("A [" + event.getChangelistName() + "] " + path + "\n"); } else if (event.getAction() == SVNEventAction.CHANGELIST_CLEAR) { buffer.append("D [" + event.getChangelistName() + "] " + path + "\n"); } else if (event.getAction() == SVNEventAction.CHANGELIST_MOVED) { myEnvironment.handleWarning(event.getErrorMessage(), new SVNErrorCode[] { event.getErrorMessage().getErrorCode() }, myEnvironment.isQuiet()); return; } else if (event.getAction() == SVNEventAction.PATCH) { myIsChangesReceived = true; if (event.getContentsStatus() == SVNStatusType.CONFLICTED) { myTextConflicts++; buffer.append('C'); } else if (event.getNodeKind() == SVNNodeKind.FILE) { if (event.getContentsStatus() == SVNStatusType.MERGED) { buffer.append('G'); } else if (event.getContentsStatus() == SVNStatusType.CHANGED) { buffer.append('U'); } } if (buffer.length() > 0) { buffer.append(' '); buffer.append(path); } } else if (event.getAction() == SVNEventAction.PATCH_APPLIED_HUNK) { myIsChangesReceived = true; final Object info = event.getInfo(); if (info == null || !(info instanceof SVNPatchHunkInfo)) { return; } final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info; final SVNPatchHunk hunk = hi.getHunk(); if (hunk.getOriginal().getStart() != hi.getMatchedLine()) { long off; String minus; if (hi.getMatchedLine() > hunk.getOriginal().getStart()) { off = hi.getMatchedLine() - hunk.getOriginal().getStart(); minus = null; } else { off = hunk.getOriginal().getStart() - hi.getMatchedLine(); minus = "-"; } buffer.append("> applied hunk @@ -"); buffer.append(hunk.getOriginal().getStart()); buffer.append(","); buffer.append(hunk.getOriginal().getLength()); buffer.append(" +"); buffer.append(hunk.getModified().getStart()); buffer.append(","); buffer.append(hunk.getModified().getLength()); buffer.append(" @@ with offset "); if (null != minus) { buffer.append(minus); } buffer.append(off); if (hi.getFuzz() > 0) { buffer.append(" and fuzz "); buffer.append(hi.getFuzz()); } buffer.append("\n"); } else if (hi.getFuzz() > 0) { buffer.append("> applied hunk @@ -"); buffer.append(hunk.getOriginal().getStart()); buffer.append(","); buffer.append(hunk.getOriginal().getLength()); buffer.append(" +"); buffer.append(hunk.getModified().getStart()); buffer.append(","); buffer.append(hunk.getModified().getLength()); buffer.append(" @@ with fuzz "); buffer.append(hi.getFuzz()); buffer.append("\n"); } } else if (event.getAction() == SVNEventAction.PATCH_REJECTED_HUNK) { myIsChangesReceived = true; final Object info = event.getInfo(); if (info == null || !(info instanceof SVNPatchHunkInfo)) { return; } final SVNPatchHunkInfo hi = (SVNPatchHunkInfo) info; final SVNPatchHunk hunk = hi.getHunk(); buffer.append("> rejected hunk @@ -"); buffer.append(hunk.getOriginal().getStart()); buffer.append(","); buffer.append(hunk.getOriginal().getLength()); buffer.append(" +"); buffer.append(hunk.getModified().getStart()); buffer.append(","); buffer.append(hunk.getModified().getLength()); buffer.append(" @@\n"); } else if (event.getAction() == SVNEventAction.UPGRADED_PATH) { myIsChangesReceived = true; buffer.append("Upgraded '" + path + "'\n"); } if (buffer.length() > 0) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.CLIENT, buffer.toString()); out.print(buffer); } } public void checkCancelled() throws SVNCancelException { myEnvironment.checkCancelled(); } public void printConflictStatus(StringBuffer buffer) { int textConflicts = 0; int propConflicts = 0; int treeConflicts = 0; int skippedPaths = 0; String header = null; header = "Summary of conflicts:\n"; textConflicts = myTextConflicts; propConflicts = myPropConflicts; treeConflicts = myTreeConflicts; skippedPaths = mySkippedPaths; if (textConflicts > 0 || propConflicts > 0 || treeConflicts > 0 || skippedPaths > 0) { buffer.append(header); } if (textConflicts > 0) { buffer.append(" Text conflicts: "); buffer.append(textConflicts); buffer.append("\n"); } if (propConflicts > 0) { buffer.append(" Property conflicts: "); buffer.append(propConflicts); buffer.append("\n"); } if (treeConflicts > 0) { buffer.append(" Tree conflicts: "); buffer.append(treeConflicts); buffer.append("\n"); } if (skippedPaths > 0) { buffer.append(" Skipped paths: "); buffer.append(skippedPaths); buffer.append("\n"); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNOption.java000066400000000000000000000157441177510526000302010ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import org.tmatesoft.svn.cli.AbstractSVNOption; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNOption extends AbstractSVNOption { public static final SVNOption VERBOSE = new SVNOption("verbose", "v"); public static final SVNOption UPDATE = new SVNOption("show-updates", "u"); public static final SVNOption NON_RECURSIVE = new SVNOption("non-recursive", "N"); public static final SVNOption DEPTH = new SVNOption("depth", false); public static final SVNOption SET_DEPTH = new SVNOption("set-depth", false); public static final SVNOption QUIET = new SVNOption("quiet", "q"); public static final SVNOption NO_IGNORE = new SVNOption("no-ignore"); public static final SVNOption INCREMENTAL = new SVNOption("incremental"); public static final SVNOption XML = new SVNOption("xml"); public static final SVNOption CONFIG_DIR = new SVNOption("config-dir", false); public static final SVNOption CONFIG_OPTION = new SVNOption("config-option", false); public static final SVNOption IGNORE_EXTERNALS = new SVNOption("ignore-externals"); public static final SVNOption IGNORE_KEYWORDS = new SVNOption("ignore-keywords"); public static final SVNOption CHANGELIST = new SVNOption("changelist", false); public static final SVNOption HELP = new SVNOption("help", "h"); public static final SVNOption QUESTION = new SVNOption(null, "?"); public static final SVNOption VERSION = new SVNOption("version"); public static final SVNOption RECURSIVE = new SVNOption("recursive", "R"); public static final SVNOption REVISION = new SVNOption("revision", "r", false); public static final SVNOption CHANGE = new SVNOption("change", "c", false); public static final SVNOption REVPROP = new SVNOption("revprop"); public static final SVNOption STRICT = new SVNOption("strict"); public static final SVNOption FILE = new SVNOption("file", "F", false); public static final SVNOption ENCODING = new SVNOption("encoding", false); public static final SVNOption TARGETS = new SVNOption("targets", false); public static final SVNOption FORCE = new SVNOption("force"); public static final SVNOption FORCE_LOG = new SVNOption("force-log"); public static final SVNOption MESSAGE = new SVNOption("message", "m", false); public static final SVNOption WITH_REVPROP = new SVNOption("with-revprop", false); public static final SVNOption EDITOR_CMD = new SVNOption("editor-cmd", false); public static final SVNOption DIFF_CMD = new SVNOption("diff-cmd", false); public static final SVNOption DIFF3_CMD = new SVNOption("diff3-cmd", false); public static final SVNOption NO_UNLOCK = new SVNOption("no-unlock"); public static final SVNOption DRY_RUN = new SVNOption("dry-run"); public static final SVNOption RECORD_ONLY = new SVNOption("record-only"); public static final SVNOption USE_MERGE_HISTORY = new SVNOption("use-merge-history", "g"); public static final SVNOption EXTENSIONS = new SVNOption("extensions", "x", false); public static final SVNOption IGNORE_ANCESTRY = new SVNOption("ignore-ancestry"); public static final SVNOption SHOW_COPIES_AS_ADDS = new SVNOption("show-copies-as-adds"); public static final SVNOption NATIVE_EOL = new SVNOption("native-eol", false); public static final SVNOption RELOCATE = new SVNOption("relocate"); public static final SVNOption AUTOPROPS = new SVNOption("auto-props"); public static final SVNOption NO_AUTOPROPS = new SVNOption("no-auto-props"); public static final SVNOption KEEP_CHANGELISTS = new SVNOption("keep-changelists"); public static final SVNOption PARENTS = new SVNOption("parents"); public static final SVNOption KEEP_LOCAL = new SVNOption("keep-local"); public static final SVNOption ACCEPT = new SVNOption("accept", false); public static final SVNOption REMOVE = new SVNOption("remove"); public static final SVNOption SHOW_REVS = new SVNOption("show-revs", false); public static final SVNOption REINTEGRATE = new SVNOption("reintegrate"); public static final SVNOption OLD = new SVNOption("old", false); public static final SVNOption NEW = new SVNOption("new", false); public static final SVNOption SUMMARIZE = new SVNOption("summarize"); public static final SVNOption NOTICE_ANCESTRY = new SVNOption("notice-ancestry"); public static final SVNOption NO_DIFF_DELETED = new SVNOption("no-diff-deleted"); public static final SVNOption STOP_ON_COPY = new SVNOption("stop-on-copy"); public static final SVNOption LIMIT = new SVNOption("limit", "l", false); public static final SVNOption AUTHOR_OF_INTEREST = new SVNOption("author", "a", false); public static final SVNOption REGULAR_EXPRESSION = new SVNOption("regexp", false); public static final SVNOption WITH_ALL_REVPROPS = new SVNOption("with-all-revprops"); public static final SVNOption WITH_NO_REVPROPS = new SVNOption("with-no-revprops"); public static final SVNOption GIT_DIFF_FORMAT = new SVNOption("git"); public static final SVNOption DIFF = new SVNOption("diff"); // auth options. public static final SVNOption USERNAME = new SVNOption("username", false); public static final SVNOption PASSWORD = new SVNOption("password", false); public static final SVNOption NO_AUTH_CACHE = new SVNOption("no-auth-cache"); public static final SVNOption NON_INTERACTIVE = new SVNOption("non-interactive"); public static final SVNOption TRUST_SERVER_CERT = new SVNOption("trust-server-cert"); public static final SVNOption STRIP = new SVNOption("strip", "p"); public static final SVNOption ALLOW_MIXED_REVISIONS = new SVNOption("allow-mixed-revisions"); public static Collection addLogMessageOptions(Collection target) { if (target != null) { target.add(MESSAGE); target.add(FILE); target.add(FORCE_LOG); target.add(EDITOR_CMD); target.add(ENCODING); target.add(WITH_REVPROP); } return target; } private SVNOption(String name) { this(name, null, true); } private SVNOption(String name, boolean unary) { this(name, null, unary); } private SVNOption(String name, String alias) { this(name, alias, true); } private SVNOption(String name, String alias, boolean unary) { super(name, alias, unary); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svn.options"; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNPatchCommand.java000066400000000000000000000052401177510526000312550ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2010 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNPatchCommand extends SVNCommand { public SVNPatchCommand() { super("patch", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.QUIET); options.add(SVNOption.DRY_RUN); options.add(SVNOption.ACCEPT); options.add(SVNOption.DIFF3_CMD); // is it opt_merge_cmd ? options.add(SVNOption.STRIP); return options; } public void run() throws SVNException { final List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); final int targetsCount = targets.size(); if (targetsCount < 1 || targetsCount > 2) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR); SVNErrorManager.error(err, SVNLogType.CLIENT); } final SVNDiffClient client = getSVNEnvironment().getClientManager().getDiffClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } final File patchPath = new File((String) targets.get(0)); final File targetPath = new File(targetsCount != 2 ? "." : (String) targets.get(1)); try { client.doPatch(patchPath.getAbsoluteFile(), targetPath.getAbsoluteFile(), getSVNEnvironment().isDryRun(), getSVNEnvironment().getStripCount()); } catch (SVNException e) { getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] { SVNErrorCode.ENTRY_EXISTS, SVNErrorCode.WC_PATH_NOT_FOUND }, getSVNEnvironment().isQuiet()); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNPropDelCommand.java000066400000000000000000000166741177510526000316000ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNPropDelCommand extends SVNPropertiesCommand { public SVNPropDelCommand() { super("propdel", new String[] {"pdel", "pd"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.QUIET); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.REVISION); options.add(SVNOption.REVPROP); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { String propertyName = getSVNEnvironment().popArgument(); if (propertyName == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } Collection targets = new ArrayList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { targets.add(""); } if (getSVNEnvironment().isRevprop()) { String target = checkRevPropTarget(getSVNEnvironment().getStartRevision(), targets); if (SVNCommandUtil.isURL(target)) { SVNURL url = SVNURL.parseURIEncoded(target); getSVNEnvironment().getClientManager().getWCClient().doSetRevisionProperty(url, getSVNEnvironment().getStartRevision(), propertyName, null, getSVNEnvironment().isForce(), this); } else { File targetFile = new SVNPath(target).getFile(); getSVNEnvironment().getClientManager().getWCClient().doSetRevisionProperty(targetFile, getSVNEnvironment().getStartRevision(), propertyName, null, getSVNEnvironment().isForce(), this); } } else if (getSVNEnvironment().getStartRevision() != SVNRevision.UNDEFINED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Cannot specify revision for deleting versioned property ''{0}''", propertyName); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } Collection changeLists = getSVNEnvironment().getChangelistsCollection(); SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); final boolean[] deletedNonExistent = new boolean[] {false}; client.setEventHandler(new ISVNEventHandler() { public void handleEvent(SVNEvent event, double progress) throws SVNException { if (event.getAction() == SVNEventAction.PROPERTY_DELETE_NONEXISTENT) { deletedNonExistent[0] = true; } } public void checkCancelled() throws SVNCancelException { getSVNEnvironment().checkCancelled(); } }); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { boolean success = true; try { if (target.isFile()){ client.doSetProperty(target.getFile(), propertyName, null, getSVNEnvironment().isForce(), depth, this, changeLists); } else { client.setCommitHandler(getSVNEnvironment()); client.doSetProperty(target.getURL(), propertyName, null, SVNRevision.HEAD, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().isForce(), this); } if (deletedNonExistent[0]) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME, "Attempting to delete nonexistent property ''{0}''", propertyName); getSVNEnvironment().getOut().println(err.getFullMessage()); success = false; } } catch (SVNException e) { success = getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.ENTRY_NOT_FOUND}, getSVNEnvironment().isQuiet()); } clearCollectedProperties(); if (success && !getSVNEnvironment().isQuiet()) { if (success) { String path = SVNCommandUtil.getLocalPath(targetName); String message = depth.isRecursive() ? "property ''{0}'' deleted (recursively) from ''{1}''." : "property ''{0}'' deleted from ''{1}''."; message = MessageFormat.format(message, new Object[] {propertyName, path}); getSVNEnvironment().getOut().println(message); } } } } } } public void handleProperty(long revision, SVNPropertyData property) throws SVNException { super.handleProperty(revision, property); if (!getSVNEnvironment().isQuiet()) { String message = "property ''{0}'' deleted from repository revision {1}"; message = MessageFormat.format(message, new Object[] {property.getName(), new Long(revision)}); getSVNEnvironment().getOut().println(message); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNPropEditCommand.java000066400000000000000000000244071177510526000317520ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNPropEditCommand extends SVNPropertiesCommand { public SVNPropEditCommand() { super("propedit", new String[]{"pedit", "pe"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.REVPROP); options = SVNOption.addLogMessageOptions(options); options.add(SVNOption.FORCE); return options; } public void run() throws SVNException { String propertyName = getSVNEnvironment().popArgument(); if (propertyName == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (!SVNPropertiesManager.isValidPropertyName(propertyName)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME, "''{0}'' is not a valid Subversion property name", propertyName); SVNErrorManager.error(err, SVNLogType.CLIENT); } Collection targets = new ArrayList(); targets = getSVNEnvironment().combineTargets(targets, true); if (getSVNEnvironment().isRevprop()) { if (targets.isEmpty()) { targets.add(""); } // SVNURL revPropURL = getRevpropURL(); SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); String target = checkRevPropTarget(getSVNEnvironment().getStartRevision(), targets); SVNURL revPropURL = null; File targetPath = null; long rev; if (SVNCommandUtil.isURL(target)) { revPropURL = SVNURL.parseURIEncoded(target); rev = client.doGetRevisionProperty(revPropURL, propertyName, getSVNEnvironment().getStartRevision(), this); } else { targetPath = new SVNPath(target).getFile(); rev = client.doGetRevisionProperty(targetPath, propertyName, getSVNEnvironment().getStartRevision(), this); } SVNPropertyData property = getRevisionProperty(rev); SVNPropertyValue propertyValue = property != null ? property.getValue() : SVNPropertyValue.create(""); byte[] propBytes = SVNPropertyValue.getPropertyAsBytes(propertyValue); byte[] bytes = SVNCommandUtil.runEditor(getSVNEnvironment(), getSVNEnvironment().getEditorCommand(), propBytes, "svn-prop"); SVNPropertyValue newPropertyValue = SVNPropertyValue.create(propertyName, bytes); if (newPropertyValue != null && !newPropertyValue.equals(propertyValue)) { clearCollectedProperties(); if (revPropURL != null) { client.doSetRevisionProperty(revPropURL, SVNRevision.create(rev), propertyName, newPropertyValue, getSVNEnvironment().isForce(), this); } else if (targetPath != null) { client.doSetRevisionProperty(targetPath, SVNRevision.create(rev), propertyName, newPropertyValue, getSVNEnvironment().isForce(), this); } String message = "Set new value for property ''{0}'' on revision {1}"; message = MessageFormat.format(message, new Object[]{propertyName, new Long(rev)}); getSVNEnvironment().getOut().println(message); } else { String message = "No changes to property ''{0}'' on revision {1}"; message = MessageFormat.format(message, new Object[]{propertyName, new Long(rev)}); getSVNEnvironment().getOut().println(message); } } else if (getSVNEnvironment().getStartRevision() != SVNRevision.UNDEFINED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Cannot specify revision for editing versioned property ''{0}''", propertyName); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { if (targets.isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Explicit target argument required", propertyName); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { if (getSVNEnvironment().getMessage() != null || getSVNEnvironment().getFileData() != null || getSVNEnvironment().getRevisionProperties() != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_UNNECESSARY_LOG_MESSAGE, "Local, non-commit operations do not take a log message or revision properties"); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPropertyData property = client.doGetProperty(target.getFile(), propertyName, SVNRevision.UNDEFINED, SVNRevision.WORKING); SVNPropertyValue propertyValue = property != null ? property.getValue() : SVNPropertyValue.create(""); byte[] propBytes = SVNPropertyValue.getPropertyAsBytes(propertyValue); byte[] bytes = SVNCommandUtil.runEditor(getSVNEnvironment(), getSVNEnvironment().getEditorCommand(), propBytes, "svn-prop"); SVNPropertyValue newPropertyValue = SVNPropertyValue.create(propertyName, bytes); if (newPropertyValue != null && !newPropertyValue.equals(propertyValue)) { checkBooleanProperty(propertyName, newPropertyValue); client.doSetProperty(target.getFile(), propertyName, newPropertyValue, getSVNEnvironment().isForce(), SVNDepth.EMPTY, this, null); String message = "Set new value for property ''{0}'' on ''{1}''"; String path = SVNCommandUtil.getLocalPath(targetName); message = MessageFormat.format(message, new Object[]{propertyName, path}); getSVNEnvironment().getOut().println(message); } else { String message = "No changes to property ''{0}'' on ''{1}''"; String path = SVNCommandUtil.getLocalPath(targetName); message = MessageFormat.format(message, new Object[]{propertyName, path}); getSVNEnvironment().getOut().println(message); } } else { SVNPropertyData property = client.doGetProperty(target.getURL(), propertyName, SVNRevision.UNDEFINED, SVNRevision.HEAD); SVNPropertyValue propertyValue = property != null ? property.getValue() : SVNPropertyValue.create(""); byte[] propBytes = SVNPropertyValue.getPropertyAsBytes(propertyValue); byte[] bytes = SVNCommandUtil.runEditor(getSVNEnvironment(), getSVNEnvironment().getEditorCommand(), propBytes, "svn-prop"); SVNPropertyValue newPropertyValue = SVNPropertyValue.create(propertyName, bytes); if (newPropertyValue != null && !newPropertyValue.equals(propertyValue)) { checkBooleanProperty(propertyName, newPropertyValue); client.setCommitHandler(getSVNEnvironment()); SVNCommitInfo info = client.doSetProperty(target.getURL(), propertyName, newPropertyValue, SVNRevision.HEAD, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().isForce(), this); String message = "Set new value for property ''{0}'' on ''{1}''"; message = MessageFormat.format(message, new Object[]{propertyName, targetName}); getSVNEnvironment().getOut().println(message); if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().printCommitInfo(info); } } else { String message = "No changes to property ''{0}'' on ''{1}''"; message = MessageFormat.format(message, new Object[]{propertyName, targetName}); getSVNEnvironment().getOut().println(message); } } clearCollectedProperties(); } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNPropGetCommand.java000066400000000000000000000224311177510526000315770ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNPropGetCommand extends SVNPropertiesCommand { public SVNPropGetCommand() { super("propget", new String[] {"pget", "pg"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.VERBOSE); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.REVISION); options.add(SVNOption.REVPROP); options.add(SVNOption.STRICT); options.add(SVNOption.XML); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { String propertyName = getSVNEnvironment().popArgument(); if (propertyName == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (!SVNPropertiesManager.isValidPropertyName(propertyName)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME, "''{0}'' is not a valid Subversion property name", propertyName); SVNErrorManager.error(err, SVNLogType.CLIENT); } Collection targets = new LinkedList(); targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { targets.add(""); } if (getSVNEnvironment().isRevprop()) { SVNWCClient wcClient = getSVNEnvironment().getClientManager().getWCClient(); String target = checkRevPropTarget(getSVNEnvironment().getStartRevision(), targets); long rev; if (SVNCommandUtil.isURL(target)) { rev = wcClient.doGetRevisionProperty(SVNURL.parseURIEncoded(target), propertyName, getSVNEnvironment().getStartRevision(), this); } else { File targetPath = new SVNPath(target).getFile(); rev = wcClient.doGetRevisionProperty(targetPath, propertyName, getSVNEnvironment().getStartRevision(), this); } SVNPropertyData propertyValue = getRevisionProperty(rev); if (propertyValue != null) { if (getSVNEnvironment().isXML()) { printXMLHeader("properties"); StringBuffer buffer = openXMLTag("revprops", SVNXMLUtil.XML_STYLE_NORMAL, "rev", Long.toString(rev), null); buffer = addXMLProp(propertyValue, buffer); buffer = closeXMLTag("revprops", buffer); getSVNEnvironment().getOut().print(buffer); printXMLFooter("properties"); } else { if (propertyValue.getValue().isString()){ getSVNEnvironment().getOut().print(propertyValue.getValue()); } else { try { getSVNEnvironment().getOut().write(propertyValue.getValue().getBytes()); } catch (IOException e) { // } } if (!getSVNEnvironment().isStrict()) { getSVNEnvironment().getOut().println(); } } } clearCollectedProperties(); } else { if (getSVNEnvironment().isXML()) { printXMLHeader("properties"); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } boolean likeProplist = getSVNEnvironment().isVerbose() && !getSVNEnvironment().isStrict(); Collection changeLists = getSVNEnvironment().getChangelistsCollection(); SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetPath = (String) ts.next(); SVNPath target = new SVNPath(targetPath, true); SVNRevision pegRevision = target.getPegRevision(); boolean printFileNames = false; if (target.isURL()) { client.doGetProperty(target.getURL(), propertyName, pegRevision, getSVNEnvironment().getStartRevision(), depth, this); printFileNames = !getSVNEnvironment().isStrict() && (getSVNEnvironment().isVerbose() || depth.compareTo(SVNDepth.EMPTY) > 0 || targets.size() > 1 || getURLProperties().size() > 1); } else { client.doGetProperty(target.getFile(), propertyName, pegRevision, getSVNEnvironment().getStartRevision(), depth, this, changeLists); printFileNames = !getSVNEnvironment().isStrict() && (getSVNEnvironment().isVerbose() || depth.compareTo(SVNDepth.EMPTY) > 0 || targets.size() > 1 || getPathProperties().size() > 1); } if (!getSVNEnvironment().isXML()) { printCollectedProperties(printFileNames, target.isURL(), likeProplist); } else { printCollectedPropertiesXML(target.isURL()); } clearCollectedProperties(); } if (getSVNEnvironment().isXML()) { printXMLFooter("properties"); } } } protected void printCollectedProperties(boolean printFileName, boolean isURL, boolean likePropList) { Map map = isURL ? getURLProperties() : getPathProperties(); for (Iterator keys = map.keySet().iterator(); keys.hasNext();) { Object key = keys.next(); List props = (List) map.get(key); if (printFileName) { if (isURL) { if (likePropList) { getSVNEnvironment().getOut().println("Properties on '" + key + "':"); } else { getSVNEnvironment().getOut().print(key); getSVNEnvironment().getOut().print(" - "); } } else { String path = SVNCommandUtil.getLocalPath(getSVNEnvironment().getRelativePath((File) key)); if (likePropList) { getSVNEnvironment().getOut().println("Properties on '" + path + "':"); } else { getSVNEnvironment().getOut().print(path); getSVNEnvironment().getOut().print(" - "); } } } if (likePropList) { printProplist(props); } else { SVNPropertyData property = (SVNPropertyData) props.get(0); printProperty(property.getValue(), likePropList); if (!getSVNEnvironment().isStrict()) { getSVNEnvironment().getOut().println(); } } } } protected void printCollectedPropertiesXML(boolean isURL) { Map map = isURL ? getURLProperties() : getPathProperties(); for (Iterator keys = map.keySet().iterator(); keys.hasNext();) { Object key = keys.next(); List props = (List) map.get(key); String target = key.toString(); if (!isURL) { target = SVNCommandUtil.getLocalPath(getSVNEnvironment().getRelativePath((File) key)); } SVNPropertyData property = (SVNPropertyData) props.get(0); StringBuffer buffer = openXMLTag("target", SVNXMLUtil.XML_STYLE_NORMAL, "path", target, null); buffer = addXMLProp(property, buffer); buffer = closeXMLTag("target", buffer); getSVNEnvironment().getOut().print(buffer); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNPropListCommand.java000066400000000000000000000223571177510526000320020ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNPropListCommand extends SVNPropertiesCommand { public SVNPropListCommand() { super("proplist", new String[] {"plist", "pl"}); } protected Collection createSupportedOptions() { Collection options = new ArrayList(); options.add(SVNOption.VERBOSE); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.REVISION); options.add(SVNOption.QUIET); options.add(SVNOption.REVPROP); options.add(SVNOption.XML); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { Collection targets = new ArrayList(); targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { targets.add(""); } if (getSVNEnvironment().isRevprop()) { SVNWCClient wcClient = getSVNEnvironment().getClientManager().getWCClient(); String target = checkRevPropTarget(getSVNEnvironment().getStartRevision(), targets); long rev; if (SVNCommandUtil.isURL(target)) { rev = wcClient.doGetRevisionProperty(SVNURL.parseURIEncoded(target), null, getSVNEnvironment().getStartRevision(), this); } else { File targetPath = new SVNPath(target).getFile(); rev = wcClient.doGetRevisionProperty(targetPath, null, getSVNEnvironment().getStartRevision(), this); } Map revisionPropertiesMap = getRevisionProperties(); List revisionProperties = (List) revisionPropertiesMap.get(new Long(rev)); if (revisionProperties == null) { revisionProperties = Collections.EMPTY_LIST; } if (getSVNEnvironment().isXML()) { printXMLHeader("properties"); StringBuffer buffer = openXMLTag("revprops", SVNXMLUtil.XML_STYLE_NORMAL, "rev", Long.toString(rev), null); for (Iterator props = revisionProperties.iterator(); props.hasNext();) { SVNPropertyData property = (SVNPropertyData) props.next(); buffer = addXMLProp(property, buffer); } buffer = closeXMLTag("revprops", buffer); getSVNEnvironment().getOut().print(buffer); printXMLFooter("properties"); } else { getSVNEnvironment().getOut().println("Unversioned properties on revision " + rev + ":"); for (Iterator props = revisionProperties.iterator(); props.hasNext();) { SVNPropertyData property = (SVNPropertyData) props.next(); getSVNEnvironment().getOut().print(" " + property.getName()); if (getSVNEnvironment().isVerbose()) { getSVNEnvironment().getOut().print(" : "); if (property.getValue().isString()){ getSVNEnvironment().getOut().print(property.getValue().getString()); } else { try { getSVNEnvironment().getOut().write(property.getValue().getBytes()); } catch (IOException e) { } } } getSVNEnvironment().getOut().println(); } } clearCollectedProperties(); } else { if (getSVNEnvironment().isXML()) { printXMLHeader("properties"); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } Collection changeLists = getSVNEnvironment().getChangelistsCollection(); SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); SVNErrorCode errorCode = null; for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetPath = (String) ts.next(); SVNPath target = new SVNPath(targetPath, true); SVNRevision pegRevision = target.getPegRevision(); try { if (target.isURL()) { client.doGetProperty(target.getURL(), null, pegRevision, getSVNEnvironment().getStartRevision(), depth, this); } else { client.doGetProperty(target.getFile(), null, pegRevision, getSVNEnvironment().getStartRevision(), depth, this, changeLists); } } catch (SVNException e) { getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.ENTRY_NOT_FOUND}, getSVNEnvironment().isQuiet()); errorCode = e.getErrorMessage().getErrorCode(); } if (!getSVNEnvironment().isXML()) { printCollectedProperties(target.isURL()); } else { printCollectedPropertiesXML(target.isURL()); } clearCollectedProperties(); } if (getSVNEnvironment().isXML()) { printXMLFooter("properties"); } if (errorCode == SVNErrorCode.UNVERSIONED_RESOURCE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not display properties of all targets because some targets don't exist"); SVNErrorManager.error(err, SVNLogType.CLIENT); } else if (errorCode == SVNErrorCode.ENTRY_NOT_FOUND) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Could not display properties of all targets because some targets are not versioned"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } protected void printCollectedProperties(boolean isURL) { Map map = isURL ? getURLProperties() : getPathProperties(); for (Iterator keys = map.keySet().iterator(); keys.hasNext();) { Object key = keys.next(); List props = (List) map.get(key); if (!getSVNEnvironment().isQuiet()) { getSVNEnvironment().getOut().print("Properties on '"); if (isURL) { getSVNEnvironment().getOut().print(key); } else { String path = SVNCommandUtil.getLocalPath(getSVNEnvironment().getRelativePath((File) key)); getSVNEnvironment().getOut().print(path); } getSVNEnvironment().getOut().println("':"); } printProplist(props); } } //TODO: in future replace all calls to this method within SVNProplistCommand with //calls to SVNXMLCommand.printXMLPropHash() protected void printCollectedPropertiesXML(boolean isURL) { Map map = isURL ? getURLProperties() : getPathProperties(); for (Iterator keys = map.keySet().iterator(); keys.hasNext();) { Object key = keys.next(); List props = (List) map.get(key); String target = key.toString(); if (!isURL) { target = SVNCommandUtil.getLocalPath(getSVNEnvironment().getRelativePath((File) key)); } StringBuffer buffer = openXMLTag("target", SVNXMLUtil.XML_STYLE_NORMAL, "path", target, null); for (Iterator plist = props.iterator(); plist.hasNext();) { SVNPropertyData property = (SVNPropertyData) plist.next(); buffer = addXMLProp(property, buffer); } buffer = closeXMLTag("target", buffer); getSVNEnvironment().getOut().print(buffer); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNPropSetCommand.java000066400000000000000000000233641177510526000316210ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNPropSetCommand extends SVNPropertiesCommand { public SVNPropSetCommand() { super("propset", new String[]{"pset", "ps"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.FILE); options.add(SVNOption.ENCODING); options.add(SVNOption.QUIET); options.add(SVNOption.REVISION); options.add(SVNOption.TARGETS); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.REVPROP); options.add(SVNOption.FORCE); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { String propertyName = getSVNEnvironment().popArgument(); if (propertyName == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (!SVNPropertiesManager.isValidPropertyName(propertyName)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME, "''{0}'' is not a valid Subversion property name", propertyName); SVNErrorManager.error(err, SVNLogType.CLIENT); } String encoding = null; if (SVNPropertiesManager.propNeedsTranslation(propertyName)) { encoding = getSVNEnvironment().getEncoding(); if (encoding == null) { encoding = "UTF-8"; } } else { if (getSVNEnvironment().getEncoding() != null) { SVNErrorMessage errorMessage = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Bad encoding option: prop value not stored as UTF8"); SVNErrorManager.error(errorMessage, SVNLogType.CLIENT); } } SVNPropertyValue propertyValue = null; if (encoding != null) { if (getSVNEnvironment().getFileData() != null) { String stringValue = null; try { stringValue = new String(getSVNEnvironment().getFileData(), encoding); } catch (UnsupportedEncodingException e) { stringValue = new String(getSVNEnvironment().getFileData()); } propertyValue = SVNPropertyValue.create(stringValue); } else { String argument = getSVNEnvironment().popArgument(); if (argument == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } propertyValue = SVNPropertyValue.create(argument); } } else { if (getSVNEnvironment().getFileData() != null) { propertyValue = SVNPropertyValue.create(propertyName, getSVNEnvironment().getFileData()); } else { String argument = getSVNEnvironment().popArgument(); if (argument == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } propertyValue = SVNPropertyValue.create(propertyName, argument.getBytes()); } } Collection targets = new ArrayList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (getSVNEnvironment().isRevprop()) { if (targets.isEmpty()) { targets.add(""); } String target = checkRevPropTarget(getSVNEnvironment().getStartRevision(), targets); if (SVNCommandUtil.isURL(target)) { SVNURL revPropURL = SVNURL.parseURIEncoded(target); getSVNEnvironment().getClientManager().getWCClient().doSetRevisionProperty(revPropURL, getSVNEnvironment().getStartRevision(), propertyName, propertyValue, getSVNEnvironment().isForce(), this); } else { File targetFile = new SVNPath(target).getFile(); getSVNEnvironment().getClientManager().getWCClient().doSetRevisionProperty(targetFile, getSVNEnvironment().getStartRevision(), propertyName, propertyValue, getSVNEnvironment().isForce(), this); } } else if (getSVNEnvironment().getStartRevision() != SVNRevision.UNDEFINED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Cannot specify revision for setting versioned property ''{0}''", propertyName); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } if (targets.isEmpty()) { if (getSVNEnvironment().getFileData() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Explicit target required (''{0}'' interpreted as prop value)", propertyValue); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Explicit target argument required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } Collection changeLists = getSVNEnvironment().getChangelistsCollection(); SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { boolean success = true; try { if (target.isFile()) { client.doSetProperty(target.getFile(), propertyName, propertyValue, getSVNEnvironment().isForce(), depth, this, changeLists); } else { client.setCommitHandler(getSVNEnvironment()); client.doSetProperty(target.getURL(), propertyName, propertyValue, SVNRevision.HEAD, getSVNEnvironment().getMessage(), getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().isForce(), this); } } catch (SVNException e) { success = getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[]{SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.ENTRY_NOT_FOUND}, getSVNEnvironment().isQuiet()); } clearCollectedProperties(); if (!getSVNEnvironment().isQuiet()) { checkBooleanProperty(propertyName, propertyValue); if (success) { String path = SVNCommandUtil.getLocalPath(targetName); String message = depth.isRecursive() ? "property ''{0}'' set (recursively) on ''{1}''" : "property ''{0}'' set on ''{1}''"; message = MessageFormat.format(message, new Object[]{propertyName, path}); getSVNEnvironment().getOut().println(message); } } } } } } public void handleProperty(long revision, SVNPropertyData property) throws SVNException { super.handleProperty(revision, property); if (!getSVNEnvironment().isQuiet()) { String message = "property ''{0}'' set on repository revision {1}"; message = MessageFormat.format(message, new Object[]{property.getName(), new Long(revision)}); getSVNEnvironment().getOut().println(message); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNPropertiesCommand.java000066400000000000000000000172341177510526000323600ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.ISVNPropertyHandler; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public abstract class SVNPropertiesCommand extends SVNXMLCommand implements ISVNPropertyHandler { private Map myRevisionProperties; private Map myURLProperties; private Map myPathProperties; protected SVNPropertiesCommand(String name, String[] aliases) { super(name, aliases); clearCollectedProperties(); } protected void clearCollectedProperties() { myRevisionProperties = new LinkedHashMap(); myURLProperties = new LinkedHashMap(); myPathProperties = new LinkedHashMap(); } protected SVNURL getRevpropURL(SVNRevision revision, Collection targets) throws SVNException { if (revision != SVNRevision.HEAD && revision.getDate() == null && revision.getNumber() < 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Must specify revision as a number, a date or 'HEAD' when operating on revision property"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (targets.size() != 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Wrong number of targets specified"); SVNErrorManager.error(err, SVNLogType.CLIENT); } String target = (String) targets.iterator().next(); return getSVNEnvironment().getURLFromTarget(target); } protected String checkRevPropTarget(SVNRevision revision, Collection targets) throws SVNException { if (revision != SVNRevision.HEAD && revision.getDate() == null && revision.getNumber() < 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Must specify revision as a number, a date or 'HEAD' when operating on revision property"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (targets.size() != 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Wrong number of targets specified"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return (String) targets.iterator().next(); } public void handleProperty(File path, SVNPropertyData property) throws SVNException { if (!myPathProperties.containsKey(path)) { myPathProperties.put(path, new LinkedList()); } ((Collection) myPathProperties.get(path)).add(property); } public void handleProperty(SVNURL url, SVNPropertyData property) throws SVNException { if (!myURLProperties.containsKey(url)) { myURLProperties.put(url, new LinkedList()); } ((Collection) myURLProperties.get(url)).add(property); } public void handleProperty(long revision, SVNPropertyData property) throws SVNException { Object key = new Long(revision); if (!myRevisionProperties.containsKey(key)) { myRevisionProperties.put(key, new LinkedList()); } ((Collection) myRevisionProperties.get(new Long(revision))).add(property); } protected SVNPropertyData getRevisionProperty(long revision) { Object key = new Long(revision); if (myRevisionProperties.containsKey(key)) { return (SVNPropertyData) ((List) myRevisionProperties.get(new Long(revision))).get(0); } return null; } protected SVNPropertyData getPathProperty(File path) { if (myPathProperties.containsKey(path)) { return (SVNPropertyData) ((List) myPathProperties.get(path)).get(0); } return null; } protected SVNPropertyData getURLProperty(SVNURL url) { if (myURLProperties.containsKey(url)) { return (SVNPropertyData) ((List) myURLProperties.get(url)).get(0); } return null; } protected Map getURLProperties() { return myURLProperties; } protected Map getPathProperties() { return myPathProperties; } protected Map getRevisionProperties() { return myRevisionProperties; } protected void printProplist(List props) { for (Iterator plist = props.iterator(); plist.hasNext();) { SVNPropertyData property = (SVNPropertyData) plist.next(); getSVNEnvironment().getOut().println(" " + property.getName()); if (getSVNEnvironment().isVerbose()) { printProperty(property.getValue(), true); } } } protected void printProperty(SVNPropertyValue value, boolean isPropListLike) { if (value.isString()) { String stringValue = value.getString(); if (isPropListLike) { stringValue += '\n'; String[] lines = SVNCommandUtil.breakToLines(stringValue); for (int i = 0; lines != null && i < lines.length; i++) { String line = lines[i]; getSVNEnvironment().getOut().print(" "); getSVNEnvironment().getOut().print(line); } } else { getSVNEnvironment().getOut().print(stringValue); } } else { try { if (isPropListLike) { //indent here getSVNEnvironment().getOut().print(" "); } getSVNEnvironment().getOut().write(value.getBytes()); if (isPropListLike) { getSVNEnvironment().getOut().println(); } } catch (IOException e) { } } } protected void checkBooleanProperty(String name, SVNPropertyValue value) throws SVNException { if (!SVNProperty.isBooleanProperty(name)) { return; } String stringValue = value.getString().trim(); if ("".equals(stringValue) || "off".equalsIgnoreCase(stringValue) || "no".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_PROPERTY_VALUE, "To turn off the {0} property, use ''svn propdel'';\n" + "setting the property to ''{1}'' will not turn it off.", new Object[]{name, value}); getSVNEnvironment().handleWarning(err, new SVNErrorCode[]{SVNErrorCode.BAD_PROPERTY_VALUE}, getSVNEnvironment().isQuiet()); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNResolveCommand.java000066400000000000000000000101421177510526000316320ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNConflictChoice; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNResolveCommand extends SVNCommand { public SVNResolveCommand() { super("resolve", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.TARGETS); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.QUIET); options.add(SVNOption.ACCEPT); return options; } public void run() throws SVNException { SVNConflictAcceptPolicy accept = getSVNEnvironment().getResolveAccept(); SVNConflictChoice choice = null; if (accept == SVNConflictAcceptPolicy.WORKING) { choice = SVNConflictChoice.MERGED; } else if (accept == SVNConflictAcceptPolicy.BASE) { choice = SVNConflictChoice.BASE; } else if (accept == SVNConflictAcceptPolicy.THEIRS_CONFLICT) { choice = SVNConflictChoice.THEIRS_CONFLICT; } else if (accept == SVNConflictAcceptPolicy.MINE_CONFLICT) { choice = SVNConflictChoice.MINE_CONFLICT; } else if (accept == SVNConflictAcceptPolicy.MINE_FULL) { choice = SVNConflictChoice.MINE_FULL; } else if (accept == SVNConflictAcceptPolicy.THEIRS_FULL) { choice = SVNConflictChoice.THEIRS_FULL; } else if (accept == null || accept == SVNConflictAcceptPolicy.UNSPECIFIED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing --accept option"); SVNErrorManager.error(err, SVNLogType.CLIENT); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid 'accept' ARG"); SVNErrorManager.error(err, SVNLogType.CLIENT); } List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { try { client.doResolve(target.getFile(), depth, choice); } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); getSVNEnvironment().handleWarning(err, new SVNErrorCode[] {err.getErrorCode()}, getSVNEnvironment().isQuiet()); } } } } }svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNResolvedCommand.java000066400000000000000000000054271177510526000320100ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNConflictChoice; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNResolvedCommand extends SVNCommand { public SVNResolvedCommand() { super("resolved", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.TARGETS); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.QUIET); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { try { client.doResolve(target.getFile(), depth, SVNConflictChoice.MERGED); } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); getSVNEnvironment().handleWarning(err, new SVNErrorCode[] {err.getErrorCode()}, getSVNEnvironment().isQuiet()); } } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNRevertCommand.java000066400000000000000000000110261177510526000314640ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry; import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNRevertCommand extends SVNCommand { public SVNRevertCommand() { super("revert", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.TARGETS); options.add(SVNOption.RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.QUIET); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNDepth depth = getSVNEnvironment().getDepth(); if (depth == SVNDepth.UNKNOWN) { depth = SVNDepth.EMPTY; } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } Collection pathsList = new ArrayList(targets.size()); for(int i = 0; i < targets.size(); i++) { SVNPath target = new SVNPath((String) targets.get(i)); if (target.isFile()) { if ("".equals(target.getTarget())) { if (isScheduledForAddition(target.getFile())) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_INVALID_OP_ON_CWD, "Cannot revert addition of current directory; please try again from the parent directory"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } pathsList.add(target.getFile()); } } Collection changeLists = getSVNEnvironment().getChangelistsCollection(); File[] paths = (File[]) pathsList.toArray(new File[pathsList.size()]); try { client.doRevert(paths, depth, changeLists); } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (!depth.isRecursive() && err.getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { err = err.wrap("Try 'svn revert --recursive' instead?"); } else if (!depth.isRecursive() && err.getErrorCode() == SVNErrorCode.WC_INVALID_OPERATION_DEPTH) { err = err.wrap("Try 'svn revert --depth infinity' instead?"); } SVNErrorManager.error(err, SVNLogType.CLIENT); } } private boolean isScheduledForAddition(File dir) { if (SVNFileType.getType(dir) != SVNFileType.DIRECTORY) { return false; } SVNWCAccess wcAccess = SVNWCAccess.newInstance(null); try { wcAccess.probeOpen(dir, false, 0); SVNEntry entry = wcAccess.getVersionedEntry(dir, false); if (entry != null && "".equals(entry.getName()) && entry.isScheduledForAddition()) { return true; } } catch (SVNException e) { } finally { try { wcAccess.close(); } catch (SVNException e) { } } return false; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNShowRevisionType.java000066400000000000000000000025551177510526000322260ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNShowRevisionType { public static final SVNShowRevisionType INVALID = new SVNShowRevisionType("invalid"); public static final SVNShowRevisionType MERGED = new SVNShowRevisionType("merged"); public static final SVNShowRevisionType ELIGIBLE = new SVNShowRevisionType("eligible"); private String myName; private SVNShowRevisionType(String name) { myName = name; } public String toString() { return myName; } public static SVNShowRevisionType fromString(String showRevisions) { if (MERGED.myName.equals(showRevisions)) { return MERGED; } else if (ELIGIBLE.myName.equals(showRevisions)) { return ELIGIBLE; } return INVALID; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNStatusCommand.java000066400000000000000000000302131177510526000314770ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.ConflictInfo; import org.tmatesoft.svn.core.wc.ISVNStatusHandler; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusClient; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNStatusCommand extends SVNXMLCommand implements ISVNStatusHandler { private SVNStatusPrinter myStatusPrinter; private Map myStatusCache; private int textConflicts; private int propConflicts; private int treeConflicts; public SVNStatusCommand() { super("status", new String[] {"stat", "st"}); } protected Collection createSupportedOptions() { Collection options = new ArrayList(); options.add(SVNOption.UPDATE); options.add(SVNOption.VERBOSE); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.QUIET); options.add(SVNOption.NO_IGNORE); options.add(SVNOption.INCREMENTAL); options.add(SVNOption.XML); options.add(SVNOption.IGNORE_EXTERNALS); options.add(SVNOption.CHANGELIST); return options; } public void run() throws SVNException { Collection targets = new ArrayList(); targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { targets.add(""); } myStatusPrinter = new SVNStatusPrinter(getSVNEnvironment()); SVNStatusClient client = getSVNEnvironment().getClientManager().getStatusClient(); if (!getSVNEnvironment().isXML()) { client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } if (getSVNEnvironment().isXML()) { if (!getSVNEnvironment().isIncremental()) { printXMLHeader("status"); } } else if (getSVNEnvironment().isIncremental()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'incremental' option only valid in XML mode"); SVNErrorManager.error(err, SVNLogType.CLIENT); } Collection changeLists = getSVNEnvironment().getChangelistsCollection(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String target = (String) ts.next(); SVNPath commandTarget = new SVNPath(target); if (getSVNEnvironment().isXML()) { StringBuffer xmlBuffer = openXMLTag("target", SVNXMLUtil.XML_STYLE_NORMAL, "path", SVNCommandUtil.getLocalPath(target), null); getSVNEnvironment().getOut().print(xmlBuffer); } try { long rev = client.doStatus(commandTarget.getFile(), SVNRevision.HEAD, getSVNEnvironment().getDepth(), getSVNEnvironment().isUpdate(), getSVNEnvironment().isVerbose(), getSVNEnvironment().isNoIgnore(), false, this, changeLists); if (getSVNEnvironment().isXML()) { StringBuffer xmlBuffer = new StringBuffer(); if (rev >= 0) { xmlBuffer = openXMLTag("against", SVNXMLUtil.XML_STYLE_SELF_CLOSING, "revision", Long.toString(rev), xmlBuffer); } xmlBuffer = closeXMLTag("target", xmlBuffer); getSVNEnvironment().getOut().print(xmlBuffer); } } catch (SVNException e) { getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.WC_NOT_DIRECTORY}, getSVNEnvironment().isQuiet()); } } if (myStatusCache != null) { for (Iterator changelists = myStatusCache.keySet().iterator(); changelists.hasNext();) { String changelist = (String) changelists.next(); Map statuses = (Map) myStatusCache.get(changelist); getSVNEnvironment().getOut().println("\n--- Changelist '" + changelist + "':"); for (Iterator paths = statuses.keySet().iterator(); paths.hasNext();) { String path = (String) paths.next(); SVNStatus status = (SVNStatus) statuses.get(path); myStatusPrinter.printStatus(path, status, getSVNEnvironment().isVerbose() || getSVNEnvironment().isUpdate(), getSVNEnvironment().isVerbose(), getSVNEnvironment().isQuiet(), getSVNEnvironment().isUpdate()); } } } if (getSVNEnvironment().isXML() && !getSVNEnvironment().isIncremental()) { printXMLFooter("status"); } if (! getSVNEnvironment().isQuiet() && ! getSVNEnvironment().isXML()) { printConflictStats(); } } public void handleStatus(SVNStatus status) throws SVNException { countConflicts(status); String path = getSVNEnvironment().getRelativePath(status.getFile()); path = SVNCommandUtil.getLocalPath(path); if (status != null && status.getChangelistName() != null) { if (myStatusCache == null) { myStatusCache = new TreeMap(); } if (!myStatusCache.containsKey(status.getChangelistName())) { myStatusCache.put(status.getChangelistName(), new LinkedHashMap()); } ((Map) myStatusCache.get(status.getChangelistName())).put(path, status); return; } if (getSVNEnvironment().isXML()) { if (SVNStatusPrinter.combineStatus(status) == SVNStatusType.STATUS_NONE && status.getRemoteContentsStatus() == SVNStatusType.STATUS_NONE) { return; } StringBuffer xmlBuffer = printXMLStatus(status, path); getSVNEnvironment().getOut().print(xmlBuffer); } else { myStatusPrinter.printStatus(path, status, getSVNEnvironment().isVerbose() || getSVNEnvironment().isUpdate(), getSVNEnvironment().isVerbose(), getSVNEnvironment().isQuiet(), getSVNEnvironment().isUpdate()); } } private void countConflicts(SVNStatus status) throws SVNException { if (status.isConflicted()) { if (status.getPropRejectFile() != null) { propConflicts++; } if (status.getConflictWrkFile() != null || status.getConflictOldFile() != null || status.getConflictNewFile() != null) { textConflicts++; } if (status.getTreeConflict() != null) { treeConflicts++; } } } protected StringBuffer printXMLStatus(SVNStatus status, String path) { StringBuffer xmlBuffer = openXMLTag("entry", SVNXMLUtil.XML_STYLE_NORMAL, "path", path, null); Map xmlMap = new LinkedHashMap(); xmlMap.put("props", status.getNodeStatus() != SVNStatusType.STATUS_DELETED ? status.getPropertiesStatus().toString() : SVNStatusType.STATUS_NONE.toString()); xmlMap.put("item", status.getCombinedNodeAndContentsStatus().toString()); if (status.isLocked()) { xmlMap.put("wc-locked", "true"); } if (status.isCopied()) { xmlMap.put("copied", "true"); } if (status.isSwitched()) { xmlMap.put("switched", "true"); } if (status.isFileExternal()) { xmlMap.put("file-external", "true"); } if (status.isVersioned() && !status.isCopied()) { xmlMap.put("revision", status.getRevision().toString()); } if (status.getTreeConflict() != null) { xmlMap.put("tree-conflicted", "true"); } xmlBuffer = openXMLTag("wc-status", SVNXMLUtil.XML_STYLE_NORMAL, xmlMap, xmlBuffer); if (status.isVersioned() && status.getCommittedRevision().isValid()) { xmlBuffer = openXMLTag("commit", SVNXMLUtil.XML_STYLE_NORMAL, "revision", status.getCommittedRevision().toString(), xmlBuffer); xmlBuffer = openCDataTag("author", status.getAuthor(), xmlBuffer); if (status.getCommittedDate() != null) { xmlBuffer = openCDataTag("date", SVNDate.formatDate(status.getCommittedDate()), xmlBuffer); } xmlBuffer = closeXMLTag("commit", xmlBuffer); } if (status.isVersioned() && status.getLocalLock() != null) { xmlBuffer = openXMLTag("lock", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); xmlBuffer = openCDataTag("token", status.getLocalLock().getID(), xmlBuffer); xmlBuffer = openCDataTag("owner", status.getLocalLock().getOwner(), xmlBuffer); xmlBuffer = openCDataTag("comment", status.getLocalLock().getComment(), xmlBuffer); xmlBuffer = openCDataTag("created", SVNDate.formatDate(status.getLocalLock().getCreationDate()), xmlBuffer); xmlBuffer = closeXMLTag("lock", xmlBuffer); } xmlBuffer = closeXMLTag("wc-status", xmlBuffer); if (status.getRemoteNodeStatus() != SVNStatusType.STATUS_NONE || status.getRemotePropertiesStatus() != SVNStatusType.STATUS_NONE || status.getRemoteLock() != null) { xmlMap.put("props", status.getRemotePropertiesStatus().toString()); xmlMap.put("item", status.getCombinedRemoteNodeAndContentsStatus().toString()); xmlBuffer = openXMLTag("repos-status", SVNXMLUtil.XML_STYLE_NORMAL, xmlMap, xmlBuffer); if (status.getRemoteLock() != null) { xmlBuffer = openXMLTag("lock", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); xmlBuffer = openCDataTag("token", status.getRemoteLock().getID(), xmlBuffer); xmlBuffer = openCDataTag("owner", status.getRemoteLock().getOwner(), xmlBuffer); xmlBuffer = openCDataTag("comment", status.getRemoteLock().getComment(), xmlBuffer); xmlBuffer = openCDataTag("created", SVNDate.formatDate(status.getRemoteLock().getCreationDate()), xmlBuffer); if (status.getRemoteLock().getExpirationDate() != null) { xmlBuffer = openCDataTag("expires", SVNDate.formatDate(status.getRemoteLock().getExpirationDate()), xmlBuffer); } xmlBuffer = closeXMLTag("lock", xmlBuffer); } xmlBuffer = closeXMLTag("repos-status", xmlBuffer); } xmlBuffer = closeXMLTag("entry", xmlBuffer); return xmlBuffer; } private void printConflictStats() { if (textConflicts > 0 || propConflicts > 0 || treeConflicts > 0) getEnvironment().getOut().println("Summary of conflicts:"); if (textConflicts > 0) getEnvironment().getOut().println( " Text conflicts: " + textConflicts); if (propConflicts > 0) getEnvironment().getOut().println( " Property conflicts: " + propConflicts); if (treeConflicts > 0) getEnvironment().getOut().println( " Tree conflicts: " + treeConflicts); } }svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNStatusPrinter.java000066400000000000000000000160311177510526000315460ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.wc.SVNTreeConflictUtil; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNStatusPrinter { private SVNCommandEnvironment myEnvironment; public SVNStatusPrinter(SVNCommandEnvironment env) { myEnvironment = env; } public void printStatus(String path, SVNStatus status, boolean detailed, boolean showLastCommitted, boolean skipUnrecognized, boolean showReposLocks) throws SVNException { if (status == null || (skipUnrecognized && !(status.isVersioned() || status.getTreeConflict() != null || status.getNodeStatus() == SVNStatusType.STATUS_EXTERNAL)) || (combineStatus(status) == SVNStatusType.STATUS_NONE && status.getRemoteContentsStatus() == SVNStatusType.STATUS_NONE)) { return; } char treeStatusCode = ' '; String treeDescriptionLine = ""; if (status.getTreeConflict() != null) { String description = SVNTreeConflictUtil.getHumanReadableConflictDescription(status.getTreeConflict()); treeStatusCode = 'C'; treeDescriptionLine = "\n > " + description; } StringBuffer result = new StringBuffer(); if (detailed) { String wcRevision; char remoteStatus; if (!status.isVersioned()) { wcRevision = ""; } else if (status.isCopied()) { wcRevision = "-"; } else if (!status.getRevision().isValid()) { if(status.getWorkingCopyFormat() == ISVNWCDb.WC_FORMAT_17) { if(status.getNodeStatus()==SVNStatusType.STATUS_DELETED) { wcRevision = status.getCommittedRevision().toString(); } else { wcRevision = "-"; } } else { wcRevision = " ? "; } } else { wcRevision = Long.toString(status.getRevision().getNumber()); } if (status.getRemoteNodeStatus() != SVNStatusType.STATUS_NONE) { remoteStatus = '*'; } else { remoteStatus = ' '; } char lockStatus; if (showReposLocks) { if (status.getRemoteLock() != null) { if (status.getLocalLock() != null) { lockStatus = status.getLocalLock().getID().equals(status.getRemoteLock().getID()) ? 'K' : 'T'; } else { lockStatus = 'O'; } } else if (status.getLocalLock() != null) { lockStatus = 'B'; } else { lockStatus = ' '; } } else { lockStatus = status.getLocalLock() != null ? 'K' : ' '; } if (showLastCommitted) { String commitRevision = ""; String commitAuthor = ""; if (status.isVersioned() && status.getCommittedRevision().isValid()) { commitRevision = status.getCommittedRevision().toString(); } else if (status.isVersioned()) { commitRevision = " ? "; } if (status.isVersioned() && status.getAuthor() != null) { commitAuthor = status.getAuthor(); } else if (status.isVersioned()) { commitAuthor = " ? "; } result.append(combineStatus(status).getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitRevision, 6, false, false)); // 6 chars result.append(" "); result.append(SVNFormatUtil.formatString(commitAuthor, 12, true)); // 12 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } else { result.append(combineStatus(status).getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(lockStatus); result.append(treeStatusCode); // tree status result.append(" "); result.append(remoteStatus); result.append(" "); result.append(SVNFormatUtil.formatString(wcRevision, 6, false, false)); // 6 chars result.append(" "); result.append(path); result.append(treeDescriptionLine); } } else { result.append(combineStatus(status).getCode()); result.append(status.getPropertiesStatus().getCode()); result.append(status.isLocked() ? 'L' : ' '); result.append(status.isCopied() ? '+' : ' '); result.append(getSwitchCharacter(status)); result.append(status.getLocalLock() != null ? 'K' : ' '); result.append(treeStatusCode); // tree status result.append(" "); result.append(path); result.append(treeDescriptionLine); } myEnvironment.getOut().println(result); } public static SVNStatusType combineStatus(SVNStatus status) { return status.getCombinedNodeAndContentsStatus(); } private static char getSwitchCharacter(SVNStatus status) { if (status == null) { return ' '; } return status.isSwitched() ? 'S' : (status.isFileExternal() ? 'X' : ' '); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNSwitchCommand.java000066400000000000000000000146041177510526000314630ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNUpdateClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNSwitchCommand extends SVNCommand { public SVNSwitchCommand() { super("switch", new String[] {"sw", "relocate"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.SET_DEPTH); options.add(SVNOption.QUIET); options.add(SVNOption.DIFF3_CMD); options.add(SVNOption.RELOCATE); options.add(SVNOption.IGNORE_EXTERNALS); options.add(SVNOption.IGNORE_ANCESTRY); options.add(SVNOption.FORCE); options.add(SVNOption.ACCEPT); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(new ArrayList(), true); if (getSVNEnvironment().isRelocate()) { if (getSVNEnvironment().getDepth() != SVNDepth.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "--relocate and --depth are mutually exclusive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } relocate(targets); return; } if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } if (targets.size() > 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR), SVNLogType.CLIENT); } SVNPath switchURL = new SVNPath((String) targets.get(0), true); if (!switchURL.isURL()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.BAD_URL, "''{0}'' doesn not appear to be a URL", switchURL.getTarget()), SVNLogType.CLIENT); } SVNPath target; if (targets.size() == 1) { target = new SVNPath(""); } else { target = new SVNPath((String) targets.get(1)); } SVNUpdateClient client = getSVNEnvironment().getClientManager().getUpdateClient(); SVNNotifyPrinter printer = new SVNNotifyPrinter(getSVNEnvironment(), false, false, false); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(printer); } SVNDepth depth = getSVNEnvironment().getDepth(); boolean depthIsSticky = false; if (getSVNEnvironment().getSetDepth() != SVNDepth.UNKNOWN) { depth = getSVNEnvironment().getSetDepth(); depthIsSticky = true; } boolean ignoreAncestry = getSVNEnvironment().isIgnoreAncestry(); client.doSwitch(target.getFile(), switchURL.getURL(), switchURL.getPegRevision(), getSVNEnvironment().getStartRevision(), depth, getSVNEnvironment().isForce(), depthIsSticky, ignoreAncestry); if (!getSVNEnvironment().isQuiet()) { StringBuffer status = new StringBuffer(); printer.printConflictStatus(status); getSVNEnvironment().getOut().print(status); } if (printer.hasExternalErrors()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ERROR_PROCESSING_EXTERNALS, "Failure occurred processing one or more externals definitions"), SVNLogType.CLIENT); } } protected void relocate(List targets) throws SVNException { if (targets.size() < 1) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNUpdateClient client = getSVNEnvironment().getClientManager().getUpdateClient(); if (targets.size() == 1 || (targets.size() == 2 && new SVNPath((String) targets.get(0)).isURL() && !new SVNPath((String) targets.get(1)).isURL())) { SVNPath target = targets.size() == 2 ? new SVNPath((String) targets.get(1)) : new SVNPath(""); SVNPath to = new SVNPath((String) targets.get(0)); client.doRelocate(target.getFile(), null, to.getURL(), getSVNEnvironment().getDepth().isRecursive()); } else { if (targets.get(0).equals(targets.get(1))) { return; } SVNPath from = new SVNPath((String) targets.get(0)); SVNPath to = new SVNPath((String) targets.get(1)); if (from.isURL() != to.isURL() || !from.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCORRECT_PARAMS, "''{0}'' to ''{1}'' is not a valid relocation", new Object[] {from.getTarget(), to.getTarget()}); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (targets.size() == 2) { SVNPath target = new SVNPath(""); client.doRelocate(target.getFile(), from.getURL(), to.getURL(), getSVNEnvironment().getDepth().isRecursive()); } else { for(int i = 2; i < targets.size(); i++) { SVNPath target = new SVNPath((String) targets.get(i)); client.doRelocate(target.getFile(), from.getURL(), to.getURL(), getSVNEnvironment().getDepth().isRecursive()); } } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNUnLockCommand.java000066400000000000000000000055601177510526000314160ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNUnLockCommand extends SVNCommand { public SVNUnLockCommand() { super("unlock", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.TARGETS); options.add(SVNOption.FORCE); return options; } public void run() throws SVNException { Collection targets = new ArrayList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT); } SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient(); SVNNotifyPrinter printer = new SVNNotifyPrinter(getSVNEnvironment()); client.setEventHandler(printer); Collection paths = new ArrayList(); Collection urls = new ArrayList(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isURL()) { urls.add(target.getURL()); } else { paths.add(target.getFile()); } } if (!paths.isEmpty()) { File[] filesArray = (File[]) paths.toArray(new File[paths.size()]); client.doUnlock(filesArray, getSVNEnvironment().isForce()); } if (!urls.isEmpty()) { SVNURL[] urlsArray = (SVNURL[]) urls.toArray(new SVNURL[urls.size()]); client.doUnlock(urlsArray, getSVNEnvironment().isForce()); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNUpdateCommand.java000066400000000000000000000135171177510526000314460ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.ISVNChangelistHandler; import org.tmatesoft.svn.core.wc.SVNChangelistClient; import org.tmatesoft.svn.core.wc.SVNUpdateClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNUpdateCommand extends SVNCommand { public SVNUpdateCommand() { super("update", new String[] {"up"}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.REVISION); options.add(SVNOption.NON_RECURSIVE); options.add(SVNOption.DEPTH); options.add(SVNOption.SET_DEPTH); options.add(SVNOption.QUIET); options.add(SVNOption.DIFF3_CMD); options.add(SVNOption.FORCE); options.add(SVNOption.IGNORE_EXTERNALS); options.add(SVNOption.CHANGELIST); options.add(SVNOption.EDITOR_CMD); options.add(SVNOption.ACCEPT); options.add(SVNOption.PARENTS); return options; } public void run() throws SVNException { List targets = new LinkedList(); if (getSVNEnvironment().getTargets() != null) { targets.addAll(getSVNEnvironment().getTargets()); } targets = getSVNEnvironment().combineTargets(targets, true); if (targets.isEmpty()) { targets.add(""); } List fileTargets = new LinkedList(); for (Iterator targetsIter = targets.iterator(); targetsIter.hasNext();) { String targetName = (String) targetsIter.next(); SVNPath target = new SVNPath(targetName); fileTargets.add(target.getFile()); } if (getSVNEnvironment().getChangelists() != null) { Collection changeLists = getSVNEnvironment().getChangelistsCollection(); SVNDepth clDepth = getSVNEnvironment().getDepth(); if (clDepth == SVNDepth.UNKNOWN) { clDepth = SVNDepth.INFINITY; } SVNChangelistClient changelistClient = getSVNEnvironment().getClientManager().getChangelistClient(); final List targetPaths = new LinkedList(); ISVNChangelistHandler handler = new ISVNChangelistHandler() { public void handle(File path, String changelistName) { targetPaths.add(path.getAbsolutePath()); } }; changelistClient.doGetChangeListPaths(changeLists, fileTargets, clDepth, handler); targets = targetPaths; } SVNUpdateClient client = getSVNEnvironment().getClientManager().getUpdateClient(); SVNNotifyPrinter printer = new SVNNotifyPrinter(getSVNEnvironment()); if (!getSVNEnvironment().isQuiet()) { client.setEventHandler(printer); } SVNDepth depth = getSVNEnvironment().getDepth(); boolean depthIsSticky = false; if (getSVNEnvironment().getSetDepth() != SVNDepth.UNKNOWN) { depth = getSVNEnvironment().getSetDepth(); depthIsSticky = true; } List files = new ArrayList(targets.size()); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (!target.isFile()) { getSVNEnvironment().getOut().println("Skipped '" + targetName + "'"); continue; } files.add(target.getFile()); } File[] filesArray = (File[]) files.toArray(new File[files.size()]); long[] results = client.doUpdate(filesArray, getSVNEnvironment().getStartRevision(), depth, getSVNEnvironment().isForce(), depthIsSticky, getSVNEnvironment().isParents()); if (!getSVNEnvironment().isQuiet()) { StringBuffer status = new StringBuffer(); printUpdateSummary(filesArray, results, status); printer.printConflictStatus(status); getSVNEnvironment().getOut().print(status); } if (printer.hasExternalErrors()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ERROR_PROCESSING_EXTERNALS, "Failure occurred processing one or more externals definitions"), SVNLogType.CLIENT); } } private void printUpdateSummary(File[] targets, long[] results, StringBuffer status) { if (targets == null || targets.length < 2 || results == null || results.length < 2) { return; } status.append("Summary of updates:\n"); for (int i = 0; i < targets.length; i++) { long rev = i < results.length ? results[i] : -1; if (rev < 0) { continue; } status.append(" Updated '" + getSVNEnvironment().getRelativePath(targets[i]) + "' to r" + rev + ".\n"); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNUpgradeCommand.java000066400000000000000000000047571177510526000316210ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc2.SvnOperationFactory; import org.tmatesoft.svn.core.wc2.SvnTarget; import org.tmatesoft.svn.core.wc2.SvnUpgrade; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNUpgradeCommand extends SVNCommand { public SVNUpgradeCommand() { super("upgrade", new String[] {}); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNOption.QUIET); options.add(SVNOption.TARGETS); return options; } public void run() throws SVNException { List targets = getSVNEnvironment().combineTargets(getSVNEnvironment().getTargets(), true); if (targets.isEmpty()) { targets.add(""); } SvnOperationFactory factory = new SvnOperationFactory(); if (!getSVNEnvironment().isQuiet()) { factory.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment())); } SvnUpgrade upgrade = factory.createUpgrade(); for (Iterator ts = targets.iterator(); ts.hasNext();) { String targetName = (String) ts.next(); SVNPath target = new SVNPath(targetName); if (target.isFile()) { getSVNEnvironment().checkCancelled(); upgrade.setSingleTarget(SvnTarget.fromFile(target.getFile())); try { upgrade.run(); } catch (SVNException e) { getSVNEnvironment().handleWarning(e.getErrorMessage(), new SVNErrorCode[] {SVNErrorCode.WC_NOT_DIRECTORY}, getSVNEnvironment().isQuiet()); } } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNXMLCommand.java000066400000000000000000000122101177510526000306510ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svn; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.nio.charset.CharsetDecoder; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import java.nio.charset.CharacterCodingException; import java.nio.ByteBuffer; import java.io.UnsupportedEncodingException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.util.SVNBase64; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.wc.SVNPropertyData; /** * @author TMate Software Ltd. * @version 1.3 */ public abstract class SVNXMLCommand extends SVNCommand { protected SVNXMLCommand(String name, String[] aliases) { super(name, aliases); } protected void printXMLHeader(String header) { StringBuffer xmlBuffer = new StringBuffer(); SVNXMLUtil.addXMLHeader(xmlBuffer, true); SVNXMLUtil.openXMLTag(null, header, SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); getSVNEnvironment().getOut().print(xmlBuffer.toString()); } protected void printXMLFooter(String header) { StringBuffer xmlBuffer = new StringBuffer(); SVNXMLUtil.closeXMLTag(null, header, xmlBuffer); getSVNEnvironment().getOut().print(xmlBuffer.toString()); } protected StringBuffer openCDataTag(String tagName, String cdata, StringBuffer target) { return SVNXMLUtil.openCDataTag(null, tagName, cdata, target); } protected StringBuffer openXMLTag(String tagName, int style, String attr, String value, StringBuffer target) { return SVNXMLUtil.openXMLTag(null, tagName, style | SVNXMLUtil.XML_STYLE_ATTRIBUTE_BREAKS_LINE, attr, value, target); } protected StringBuffer openXMLTag(String tagName, int style, Map attributes, StringBuffer target) { return SVNXMLUtil.openXMLTag(null, tagName, style | SVNXMLUtil.XML_STYLE_ATTRIBUTE_BREAKS_LINE, attributes, target); } protected StringBuffer closeXMLTag(String tagName, StringBuffer target) { return SVNXMLUtil.closeXMLTag(null, tagName, target); } protected StringBuffer printXMLPropHash(StringBuffer buffer, SVNProperties propHash, boolean namesOnly) { if (propHash != null && !propHash.isEmpty()) { buffer = buffer == null ? new StringBuffer() : buffer; for (Iterator propNames = propHash.nameSet().iterator(); propNames.hasNext();) { String propName = (String) propNames.next(); SVNPropertyValue propVal = propHash.getSVNPropertyValue(propName); if (namesOnly) { buffer = openXMLTag("property", SVNXMLUtil.XML_STYLE_SELF_CLOSING, "name", propName, buffer); } else { buffer = addXMLProp(new SVNPropertyData(propName, propVal, null), buffer); } } } return buffer; } protected StringBuffer addXMLProp(SVNPropertyData property, StringBuffer xmlBuffer) { String value = property.getValue().getString(); value = value == null ? "" : value; boolean isXMLSafe = true; if (property.getValue().isBinary()) { CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); try { value = decoder.decode(ByteBuffer.wrap(property.getValue().getBytes())).toString(); } catch (CharacterCodingException e) { isXMLSafe = false; } } if (value != null && isXMLSafe) { isXMLSafe = SVNEncodingUtil.isXMLSafe(value); } Map attrs = new TreeMap(); attrs.put("name", property.getName()); if (!isXMLSafe) { attrs.put("encoding", "base64"); if (value != null) { try { value = SVNBase64.byteArrayToBase64(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { value = SVNBase64.byteArrayToBase64(value.getBytes()); } } else { value = SVNBase64.byteArrayToBase64(property.getValue().getBytes()); } } value = SVNEncodingUtil.xmlEncodeCDATA(value); xmlBuffer = openXMLTag("property", SVNXMLUtil.XML_STYLE_PROTECT_CDATA, attrs, xmlBuffer); xmlBuffer.append(value); xmlBuffer = closeXMLTag("property", xmlBuffer); return xmlBuffer; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/000077500000000000000000000000001177510526000264755ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdmin.java000066400000000000000000000101651177510526000307620ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNLauncher; import org.tmatesoft.svn.cli.SVNCommandLine; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdmin extends AbstractSVNLauncher { public static void main(String[] args) { new SVNAdmin().run(args); } protected AbstractSVNCommandEnvironment createCommandEnvironment() { return new SVNAdminCommandEnvironment(getProgramName(), System.out, System.err, System.in); } protected String getProgramName() { return "jsvnadmin"; } protected boolean needArgs() { return true; } protected boolean needCommand() { return true; } protected void registerCommands() { AbstractSVNCommand.registerCommand(new SVNAdminHelpCommand()); AbstractSVNCommand.registerCommand(new SVNAdminCreateCommand()); AbstractSVNCommand.registerCommand(new SVNAdminDumpCommand()); AbstractSVNCommand.registerCommand(new SVNAdminListLocksCommand()); AbstractSVNCommand.registerCommand(new SVNAdminListTransactionsCommand()); AbstractSVNCommand.registerCommand(new SVNAdminLoadCommand()); AbstractSVNCommand.registerCommand(new SVNAdminRemoveLocksCommand()); AbstractSVNCommand.registerCommand(new SVNAdminRemoveTransactionsCommand()); AbstractSVNCommand.registerCommand(new SVNAdminSetLogCommand()); AbstractSVNCommand.registerCommand(new SVNAdminSetRevPropCommand()); AbstractSVNCommand.registerCommand(new SVNAdminVerifyCommand()); AbstractSVNCommand.registerCommand(new SVNAdminRecoverCommand()); AbstractSVNCommand.registerCommand(new SVNAdminUpgradeCommand()); AbstractSVNCommand.registerCommand(new SVNAdminSetUUIDCommand()); AbstractSVNCommand.registerCommand(new SVNAdminHotCopyCommand()); AbstractSVNCommand.registerCommand(new SVNAdminPackCommand()); } protected void registerOptions() { SVNCommandLine.registerOption(SVNAdminOption.HELP); SVNCommandLine.registerOption(SVNAdminOption.QUESTION); SVNCommandLine.registerOption(SVNAdminOption.VERSION); SVNCommandLine.registerOption(SVNAdminOption.REVISION); SVNCommandLine.registerOption(SVNAdminOption.INCREMENTAL); SVNCommandLine.registerOption(SVNAdminOption.DELTAS); SVNCommandLine.registerOption(SVNAdminOption.BYPASS_HOOKS); SVNCommandLine.registerOption(SVNAdminOption.QUIET); SVNCommandLine.registerOption(SVNAdminOption.IGNORE_UUID); SVNCommandLine.registerOption(SVNAdminOption.FORCE_UUID); SVNCommandLine.registerOption(SVNAdminOption.PARENT_DIR); SVNCommandLine.registerOption(SVNAdminOption.FS_TYPE); SVNCommandLine.registerOption(SVNAdminOption.BDB_TXN_NOSYNC); SVNCommandLine.registerOption(SVNAdminOption.BDB_LOG_KEEP); SVNCommandLine.registerOption(SVNAdminOption.CONFIG_DIR); SVNCommandLine.registerOption(SVNAdminOption.CLEAN_LOGS); SVNCommandLine.registerOption(SVNAdminOption.USE_PRE_COMMIT_HOOK); SVNCommandLine.registerOption(SVNAdminOption.USE_POST_COMMIT_HOOK); SVNCommandLine.registerOption(SVNAdminOption.USE_PRE_REVPROP_CHANGE_HOOK); SVNCommandLine.registerOption(SVNAdminOption.USE_POST_REVPROP_CHANGE_HOOK); SVNCommandLine.registerOption(SVNAdminOption.WAIT); SVNCommandLine.registerOption(SVNAdminOption.PRE_14_COMPATIBLE); SVNCommandLine.registerOption(SVNAdminOption.PRE_15_COMPATIBLE); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminCommand.java000066400000000000000000000066501177510526000322650ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.List; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class SVNAdminCommand extends AbstractSVNCommand { protected SVNAdminCommand(String name, String[] aliases) { super(name, aliases); } protected SVNAdminCommandEnvironment getSVNAdminEnvironment() { return (SVNAdminCommandEnvironment) getEnvironment(); } protected File getLocalRepository() throws SVNException { return getLocalRepository(0); } protected File getLocalRepository(int index) throws SVNException { List targets = getEnvironment().combineTargets(null, false); if (targets.isEmpty()) { targets.add(""); } if (targets.isEmpty() || index > targets.size() - 1 ) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Repository argument required"), SVNLogType.CLIENT); } SVNPath target = new SVNPath((String) targets.get(index)); if (target.isURL()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "'" + target.getTarget() + "' is an URL when it should be a path"), SVNLogType.CLIENT); } return target.getFile(); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnadmin.commands"; } protected long getRevisionNumber(SVNRevision rev, long latestRevision, SVNRepository repos) throws SVNException { long result = -1; if (rev.getNumber() >= 0) { result = rev.getNumber(); } else if (rev == SVNRevision.HEAD) { result = latestRevision; } else if (rev.getDate() != null) { result = repos.getDatedRevision(rev.getDate()); } else if (rev != SVNRevision.UNDEFINED) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Invalid revision specifier"), SVNLogType.CLIENT); } if (result > latestRevision) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Revisions must not be greater than the youngest revision (" + latestRevision + ")"), SVNLogType.CLIENT); } return result; } public Collection getGlobalOptions() { return Collections.EMPTY_LIST; } } SVNAdminCommandEnvironment.java000066400000000000000000000241201177510526000344230ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNOption; import org.tmatesoft.svn.cli.SVNCommandLine; import org.tmatesoft.svn.cli.SVNOptionValue; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminCommandEnvironment extends AbstractSVNCommandEnvironment { private boolean myIsQuiet; private boolean myIsHelp; private boolean myIsVersion; private String myParentDir; private boolean myIsIncremental; private boolean myIsDeltas; private boolean myIsIgnoreUUID; private boolean myIsForceUUID; private boolean myIsPre14Compatible; private boolean myIsPre15Compatible; private boolean myIsPre16Compatible; private boolean myIsPre17Compatible; private boolean myIsWith17Compatible; private boolean myIsUsePreCommitHook; private boolean myIsUsePostCommitHook; private boolean myIsUsePostRevPropChangeHook; private boolean myIsUsePreRevPropChangeHook; private boolean myIsBypassHooks; private boolean myIsCleanLogs; private String myConfigDir; private boolean myIsWait; private SVNRevision myStartRevision; private SVNRevision myEndRevision; protected SVNAdminCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { super(programName, out, err, in); myStartRevision = SVNRevision.UNDEFINED; myEndRevision = SVNRevision.UNDEFINED; } protected ISVNAuthenticationManager createClientAuthenticationManager() { File configDir = myConfigDir != null ? new File(myConfigDir).getAbsoluteFile() : null; return SVNWCUtil.createDefaultAuthenticationManager(configDir); } protected DefaultSVNOptions createClientOptions() { File configDir = myConfigDir != null ? new File(myConfigDir).getAbsoluteFile() : null; return SVNWCUtil.createDefaultOptions(configDir, true); } protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNAdminOption.REVISION) { if (myStartRevision != SVNRevision.UNDEFINED) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Multiple revision argument encountered; " + "can't specify -r and c, or try '-r N:M' instead of '-r N -r M'"); SVNErrorManager.error(err, SVNLogType.CLIENT); } String revStr = optionValue.getValue(); SVNRevision[] revisions = parseRevision(revStr); if (revisions == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Syntax error in revision argument ''{0}''", revStr); SVNErrorManager.error(err, SVNLogType.CLIENT); } myStartRevision = revisions[0]; myEndRevision = revisions[1]; } else if (option == SVNAdminOption.QUIET) { myIsQuiet = true; } else if (option == SVNAdminOption.HELP || option == SVNAdminOption.QUESTION) { myIsHelp = true; } else if (option == SVNAdminOption.VERSION) { myIsVersion = true; } else if (option == SVNAdminOption.INCREMENTAL) { myIsIncremental = true; } else if (option == SVNAdminOption.DELTAS) { myIsDeltas = true; } else if (option == SVNAdminOption.IGNORE_UUID) { myIsIgnoreUUID = true; } else if (option == SVNAdminOption.FORCE_UUID) { myIsForceUUID = true; } else if (option == SVNAdminOption.PRE_14_COMPATIBLE) { myIsPre14Compatible = true; } else if (option == SVNAdminOption.PRE_15_COMPATIBLE) { myIsPre15Compatible = true; } else if (option == SVNAdminOption.PRE_16_COMPATIBLE) { myIsPre16Compatible = true; } else if (option == SVNAdminOption.PRE_17_COMPATIBLE) { myIsPre17Compatible = true; } else if (option == SVNAdminOption.WITH_17_COMPATIBLE) { myIsWith17Compatible = true; } else if (option == SVNAdminOption.PARENT_DIR) { myParentDir = optionValue.getValue(); myParentDir = myParentDir.replace(File.separatorChar, '/'); myParentDir = SVNPathUtil.canonicalizePath(myParentDir); } else if (option == SVNAdminOption.USE_PRE_COMMIT_HOOK) { myIsUsePreCommitHook = true; } else if (option == SVNAdminOption.USE_POST_COMMIT_HOOK) { myIsUsePostCommitHook = true; } else if (option == SVNAdminOption.USE_POST_REVPROP_CHANGE_HOOK) { myIsUsePostRevPropChangeHook = true; } else if (option == SVNAdminOption.USE_PRE_REVPROP_CHANGE_HOOK) { myIsUsePreRevPropChangeHook = true; } else if (option == SVNAdminOption.BYPASS_HOOKS) { myIsBypassHooks = true; } else if (option == SVNAdminOption.CLEAN_LOGS) { myIsCleanLogs = true; } else if (option == SVNAdminOption.CONFIG_DIR) { myConfigDir = optionValue.getValue(); } else if (option == SVNAdminOption.WAIT) { myIsWait = true; } } protected String refineCommandName(String commandName, SVNCommandLine commandLine) throws SVNException { for (Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); AbstractSVNOption option = optionValue.getOption(); if (option == SVNAdminOption.HELP || option == SVNAdminOption.QUESTION) { myIsHelp = true; } else if (option == SVNAdminOption.VERSION) { myIsVersion = true; } } if (myIsHelp) { List newArguments = commandName != null ? Collections.singletonList(commandName) : Collections.EMPTY_LIST; setArguments(newArguments); return "help"; } if (commandName == null) { if (isVersion()) { SVNAdminCommand versionCommand = new SVNAdminCommand("--version", null) { protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNAdminOption.VERSION); options.add(SVNAdminOption.QUIET); return options; } public void run() throws SVNException { AbstractSVNCommand helpCommand = AbstractSVNCommand.getCommand("help"); helpCommand.init(SVNAdminCommandEnvironment.this); helpCommand.run(); } }; AbstractSVNCommand.registerCommand(versionCommand); return "--version"; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Subcommand argument required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return commandName; } protected String getCommandLineClientName() { return "svnadmin"; } public boolean isQuiet() { return myIsQuiet; } public boolean isHelp() { return myIsHelp; } public boolean isVersion() { return myIsVersion; } public String getParentDir() { return myParentDir; } public boolean isIncremental() { return myIsIncremental; } public boolean isDeltas() { return myIsDeltas; } public boolean isIgnoreUUID() { return myIsIgnoreUUID; } public boolean isForceUUID() { return myIsForceUUID; } public boolean isPre14Compatible() { return myIsPre14Compatible; } public boolean isPre15Compatible() { return myIsPre15Compatible; } public boolean isPre16Compatible() { return myIsPre16Compatible; } public boolean isPre17Compatible() { return myIsPre17Compatible; } public boolean isWith17Compatible() { return myIsWith17Compatible; } public boolean isUsePreCommitHook() { return myIsUsePreCommitHook; } public boolean isUsePostCommitHook() { return myIsUsePostCommitHook; } public boolean isUsePostRevPropChangeHook() { return myIsUsePostRevPropChangeHook; } public boolean isUsePreRevPropChangeHook() { return myIsUsePreRevPropChangeHook; } public boolean isBypassHooks() { return myIsBypassHooks; } public boolean isCleanLogs() { return myIsCleanLogs; } public boolean isWait() { return myIsWait; } public SVNRevision getStartRevision() { return myStartRevision; } public SVNRevision getEndRevision() { return myEndRevision; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminCreateCommand.java000066400000000000000000000037241177510526000334100ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminCreateCommand extends SVNAdminCommand { public SVNAdminCreateCommand() { super("create", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNAdminOption.BDB_TXN_NOSYNC); options.add(SVNAdminOption.BDB_LOG_KEEP); options.add(SVNAdminOption.CONFIG_DIR); options.add(SVNAdminOption.FS_TYPE); options.add(SVNAdminOption.PRE_14_COMPATIBLE); options.add(SVNAdminOption.PRE_15_COMPATIBLE); options.add(SVNAdminOption.PRE_16_COMPATIBLE); options.add(SVNAdminOption.PRE_17_COMPATIBLE); options.add(SVNAdminOption.WITH_17_COMPATIBLE); return options; } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.doCreateRepository(getLocalRepository(), null, false, false, getSVNAdminEnvironment().isPre14Compatible(), getSVNAdminEnvironment().isPre15Compatible(), getSVNAdminEnvironment().isPre16Compatible(), getSVNAdminEnvironment().isPre17Compatible(), getSVNAdminEnvironment().isWith17Compatible() ); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminDumpCommand.java000066400000000000000000000074701177510526000331140ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminDumpCommand extends SVNAdminCommand implements ISVNAdminEventHandler { public SVNAdminDumpCommand() { super("dump", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNAdminOption.REVISION); options.add(SVNAdminOption.INCREMENTAL); options.add(SVNAdminOption.DELTAS); options.add(SVNAdminOption.QUIET); return options; } public void run() throws SVNException { SVNRevision start = getSVNAdminEnvironment().getStartRevision(); SVNRevision end = getSVNAdminEnvironment().getEndRevision(); SVNURL url = SVNURL.fromFile(getLocalRepository()); SVNRepository repository = SVNRepositoryFactory.create(url); repository.setCanceller(getEnvironment()); long latestRevision = repository.getLatestRevision(); long startRev = getRevisionNumber(start, latestRevision, repository); long endRev = getRevisionNumber(end, latestRevision, repository); if (startRev < 0) { startRev = 0; endRev = latestRevision; } else if (endRev < 0) { endRev = startRev; } if (startRev > endRev) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "First revision cannot be higher than second"), SVNLogType.CLIENT); } boolean incremental = getSVNAdminEnvironment().isIncremental(); boolean deltas = getSVNAdminEnvironment().isDeltas(); SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); if (!getSVNAdminEnvironment().isQuiet()) { client.setEventHandler(this); } start = SVNRevision.create(startRev); end = SVNRevision.create(endRev); client.doDump(getLocalRepository(), getEnvironment().getOut(), start, end, incremental, deltas); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event != null && event.getAction() == SVNAdminEventAction.REVISION_DUMPED) { getEnvironment().getErr().println(event.getMessage()); } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminHelpCommand.java000066400000000000000000000063331177510526000330740ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.text.MessageFormat; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminHelpCommand extends SVNAdminCommand { private static final String GENERIC_HELP_HEADER = "general usage: {0} SUBCOMMAND REPOS_PATH [ARGS & OPTIONS ...]\n" + "Type ''{0} help '' for help on a specific subcommand.\n" + "Type ''{0} --version'' to see the program version and FS modules.\n" + "\n" + "Available subcommands:"; private static final String VERSION_HELP_FOOTER = "\nThe following repository back-end (FS) modules are available:\n\n" + "* fs_fs : Module for working with a plain file (FSFS) repository."; public SVNAdminHelpCommand() { super("help", new String[] {"?", "h"}); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { if (!getEnvironment().getArguments().isEmpty()) { for (Iterator commands = getEnvironment().getArguments().iterator(); commands.hasNext();) { String commandName = (String) commands.next(); AbstractSVNCommand command = AbstractSVNCommand.getCommand(commandName); if (command == null) { getEnvironment().getErr().println("\"" + commandName + "\": unknown command.\n"); continue; } getEnvironment().getProgramName(); String help = SVNCommandUtil.getCommandHelp(command, getEnvironment().getProgramName(), true); getEnvironment().getOut().println(help); } } else if (getSVNAdminEnvironment().isVersion()) { String version = SVNCommandUtil.getVersion(getEnvironment(), getSVNAdminEnvironment().isQuiet()); getEnvironment().getOut().println(version); if (!getSVNAdminEnvironment().isQuiet()) { getEnvironment().getOut().println(VERSION_HELP_FOOTER); } } else if (getEnvironment().getArguments().isEmpty()) { String help = SVNCommandUtil.getGenericHelp(getEnvironment().getProgramName(), GENERIC_HELP_HEADER, null, null); getEnvironment().getOut().print(help); } else { String message = MessageFormat.format("Type ''{0} help'' for usage.", new Object[] {getEnvironment().getProgramName()}); getEnvironment().getOut().println(message); } } } SVNAdminHotCopyCommand.java000066400000000000000000000024421177510526000335070ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminHotCopyCommand extends SVNAdminCommand { public SVNAdminHotCopyCommand() { super("hotcopy", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNAdminOption.CLEAN_LOGS); return options; } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.doHotCopy(getLocalRepository(), getLocalRepository(1)); } } SVNAdminListLocksCommand.java000066400000000000000000000055171177510526000340370ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.ISVNOptions; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminListLocksCommand extends SVNAdminCommand { public SVNAdminListLocksCommand() { super("lslocks", null); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { ISVNOptions options = getEnvironment().getClientManager().getOptions(); SVNURL url = SVNURL.fromFile(getLocalRepository()); SVNRepository repository = SVNRepositoryFactory.create(url); repository.setCanceller(getEnvironment()); SVNLock[] locks = repository.getLocks("/"); for (int i = 0; locks != null && i < locks.length; i++) { SVNLock lock = locks[i]; StringBuffer buffer = new StringBuffer(); String comment = "(0 lines):"; if (lock.getComment() != null) { int count = SVNCommandUtil.getLinesCount(lock.getComment()); comment = count != 1 ? count + " lines" : count + " line"; comment = "(" + comment + "):\n" + lock.getComment(); } String created = lock.getCreationDate() != null ? SVNDate.formatHumanDate(lock.getCreationDate(), options) : ""; String expires = lock.getExpirationDate() != null ? SVNDate.formatHumanDate(lock.getExpirationDate(), options) : ""; buffer.append("Path: " + lock.getPath() + "\n"); buffer.append("UUID Token: " + lock.getID() + "\n"); buffer.append("Owner: " + lock.getOwner() + "\n"); buffer.append("Created: " + created + "\n"); buffer.append("Expires: " + expires + "\n"); buffer.append("Comment " + comment + "\n\n"); getEnvironment().getOut().print(buffer.toString()); } } } SVNAdminListTransactionsCommand.java000066400000000000000000000040061177510526000354240ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminListTransactionsCommand extends SVNAdminCommand implements ISVNAdminEventHandler { public SVNAdminListTransactionsCommand() { super("lstxns", null); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.doListTransactions(getLocalRepository()); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event != null && event.getAction() == SVNAdminEventAction.TRANSACTION_LISTED) { getEnvironment().getOut().print(event.getTxnName() + "\n"); } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminLoadCommand.java000066400000000000000000000066461177510526000330720ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.core.wc.admin.SVNUUIDAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminLoadCommand extends SVNAdminCommand implements ISVNAdminEventHandler { private boolean myIsNodeOpened; public SVNAdminLoadCommand() { super("load", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNAdminOption.QUIET); options.add(SVNAdminOption.IGNORE_UUID); options.add(SVNAdminOption.FORCE_UUID); options.add(SVNAdminOption.USE_PRE_COMMIT_HOOK); options.add(SVNAdminOption.USE_POST_COMMIT_HOOK); options.add(SVNAdminOption.PARENT_DIR); return options; } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); if (!getSVNAdminEnvironment().isQuiet()) { client.setEventHandler(this); } SVNUUIDAction uuidAction = SVNUUIDAction.DEFAULT; if (getSVNAdminEnvironment().isForceUUID()) { uuidAction = SVNUUIDAction.FORCE_UUID; } else if (getSVNAdminEnvironment().isIgnoreUUID()) { uuidAction = SVNUUIDAction.IGNORE_UUID; } client.doLoad(getLocalRepository(), getEnvironment().getIn(), getSVNAdminEnvironment().isUsePreCommitHook(), getSVNAdminEnvironment().isUsePostCommitHook(), uuidAction, getSVNAdminEnvironment().getParentDir()); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() != SVNAdminEventAction.REVISION_LOAD && myIsNodeOpened) { getEnvironment().getOut().println(" done."); myIsNodeOpened = false; } if (event.getAction() == SVNAdminEventAction.REVISION_LOADED) { getEnvironment().getOut().println(); } getEnvironment().getOut().print(event.getMessage()); if (event.getAction() == SVNAdminEventAction.REVISION_LOADED || event.getAction() == SVNAdminEventAction.REVISION_LOAD) { getEnvironment().getOut().println(); } myIsNodeOpened = event.getAction() != SVNAdminEventAction.REVISION_LOAD; } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminOption.java000066400000000000000000000067701177510526000321620ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import org.tmatesoft.svn.cli.AbstractSVNOption; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminOption extends AbstractSVNOption { public static final SVNAdminOption HELP = new SVNAdminOption("help", "h"); public static final SVNAdminOption QUESTION = new SVNAdminOption(null, "?"); public static final SVNAdminOption VERSION = new SVNAdminOption("version"); public static final SVNAdminOption REVISION = new SVNAdminOption("revision", "r", false); public static final SVNAdminOption INCREMENTAL = new SVNAdminOption("incremental"); public static final SVNAdminOption DELTAS = new SVNAdminOption("deltas"); public static final SVNAdminOption BYPASS_HOOKS = new SVNAdminOption("bypass-hooks"); public static final SVNAdminOption QUIET = new SVNAdminOption("quiet", "q"); public static final SVNAdminOption IGNORE_UUID = new SVNAdminOption("ignore-uuid"); public static final SVNAdminOption FORCE_UUID = new SVNAdminOption("force-uuid"); public static final SVNAdminOption PARENT_DIR = new SVNAdminOption("parent-dir", null, false); public static final SVNAdminOption FS_TYPE = new SVNAdminOption("fs-type", null, false); public static final SVNAdminOption BDB_TXN_NOSYNC = new SVNAdminOption("bdb-txn-nosync"); public static final SVNAdminOption BDB_LOG_KEEP = new SVNAdminOption("bdb-log-keep"); public static final SVNAdminOption CONFIG_DIR = new SVNAdminOption("config-dir", null, false); public static final SVNAdminOption CLEAN_LOGS = new SVNAdminOption("clean-logs"); public static final SVNAdminOption USE_PRE_COMMIT_HOOK = new SVNAdminOption("use-pre-commit-hook"); public static final SVNAdminOption USE_POST_COMMIT_HOOK = new SVNAdminOption("use-post-commit-hook"); public static final SVNAdminOption USE_PRE_REVPROP_CHANGE_HOOK = new SVNAdminOption("use-pre-revprop-change-hook"); public static final SVNAdminOption USE_POST_REVPROP_CHANGE_HOOK = new SVNAdminOption("use-post-revprop-change-hook"); public static final SVNAdminOption WAIT = new SVNAdminOption("wait"); public static final SVNAdminOption PRE_14_COMPATIBLE = new SVNAdminOption("pre-1.4-compatible"); public static final SVNAdminOption PRE_15_COMPATIBLE = new SVNAdminOption("pre-1.5-compatible"); public static final SVNAdminOption PRE_16_COMPATIBLE = new SVNAdminOption("pre-1.6-compatible"); public static final SVNAdminOption PRE_17_COMPATIBLE = new SVNAdminOption("pre-1.7-compatible"); public static final SVNAdminOption WITH_17_COMPATIBLE = new SVNAdminOption("with-1.7-compatible"); private SVNAdminOption(String name) { this(name, null, true); } private SVNAdminOption(String name, String alias) { this(name, alias, true); } private SVNAdminOption(String name, String alias, boolean unary) { super(name, alias, unary); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnadmin.options"; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminPackCommand.java000066400000000000000000000040541177510526000330600ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminPackCommand extends SVNAdminCommand implements ISVNAdminEventHandler { public SVNAdminPackCommand() { super("pack", null); } protected Collection createSupportedOptions() { return null; } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.doPack(getLocalRepository()); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.PACK_START) { getEnvironment().getOut().print("Packing shard " + event.getShard() + "..."); } else if (event.getAction() == SVNAdminEventAction.PACK_END) { getEnvironment().getOut().println("done."); } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } SVNAdminRecoverCommand.java000066400000000000000000000051131177510526000335250ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.text.MessageFormat; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminRecoverCommand extends SVNAdminCommand implements ISVNAdminEventHandler { public SVNAdminRecoverCommand() { super("recover", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNAdminOption.WAIT); return options; } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.doRecover(getLocalRepository()); getEnvironment().getOut().println(); getEnvironment().getOut().println("Recovery completed."); long youngestRevision = client.getYoungestRevision(getLocalRepository()); String message = "The latest repos revision is {0}."; message = MessageFormat.format(message, new Object[] { String.valueOf(youngestRevision) }); getEnvironment().getOut().println(message); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.RECOVERY_STARTED) { getEnvironment().getOut().println("Repository lock acquired."); getEnvironment().getOut().println("Please wait; recovering the repository may take some time..."); } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } SVNAdminRemoveLocksCommand.java000066400000000000000000000060251177510526000343540ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.BasicAuthenticationManager; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.io.ISVNLockHandler; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminRemoveLocksCommand extends SVNAdminCommand implements ISVNLockHandler { public SVNAdminRemoveLocksCommand() { super("rmlocks", null); } protected Collection createSupportedOptions() { return new ArrayList(); } public void run() throws SVNException { List targets = getEnvironment().combineTargets(null, false); if (!targets.isEmpty()) { targets.remove(0); } String[] locks = (String[]) targets.toArray(new String[targets.size()]); SVNRepository repository = SVNRepositoryFactory.create(SVNURL.fromFile(getLocalRepository())); String userName = System.getProperty("user.name", "administrator"); repository.setAuthenticationManager(new BasicAuthenticationManager(userName, "")); repository.setCanceller(getEnvironment()); for (int i = 0; i < locks.length; i++) { String lockPath = locks[i]; try { SVNLock lock = repository.getLock(lockPath); if (lock == null) { getEnvironment().getOut().println("Path '" + lockPath + "' isn't locked."); continue; } Map pathToToken = new SVNHashMap(); pathToToken.put(lockPath, lock.getID()); repository.unlock(pathToToken, true, this); } catch (SVNException e) { getEnvironment().handleError(e.getErrorMessage()); } } } public void handleLock(String path, SVNLock lock, SVNErrorMessage error) throws SVNException { } public void handleUnlock(String path, SVNLock lock, SVNErrorMessage error) throws SVNException { if (error != null) { getEnvironment().handleError(error); } else { getEnvironment().getOut().println("Removed lock on '" + path + "'."); } } } SVNAdminRemoveTransactionsCommand.java000066400000000000000000000051351177510526000357520ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminRemoveTransactionsCommand extends SVNAdminCommand implements ISVNAdminEventHandler { public SVNAdminRemoveTransactionsCommand() { super("rmtxns", null); } protected Collection createSupportedOptions() { List options = new ArrayList(); options.add(SVNAdminOption.QUIET); return options; } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); List targets = getEnvironment().combineTargets(null, false); if (!targets.isEmpty()) { targets.remove(0); } String[] transactions = (String[]) targets.toArray(new String[targets.size()]); client.setEventHandler(this); client.doRemoveTransactions(getLocalRepository(), transactions); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event != null && event.getAction() == SVNAdminEventAction.TRANSACTION_REMOVED) { if (!getSVNAdminEnvironment().isQuiet()) { String txnName = event.getTxnName(); getEnvironment().getOut().println("Transaction '" + txnName + "' removed."); } } else if (event.getError() != null) { getEnvironment().handleError(event.getError()); } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminSetLogCommand.java000066400000000000000000000065311177510526000334010ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.io.File; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminSetLogCommand extends SVNAdminCommand { public SVNAdminSetLogCommand() { super("setlog", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNAdminOption.REVISION); options.add(SVNAdminOption.BYPASS_HOOKS); return options; } public void run() throws SVNException { if (getSVNAdminEnvironment().getStartRevision() == SVNRevision.UNDEFINED) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Missing revision"), SVNLogType.CLIENT); } if (getSVNAdminEnvironment().getEndRevision() != SVNRevision.UNDEFINED) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Only one revision allowed"), SVNLogType.CLIENT); } File repos = getLocalRepository(); List targets = getEnvironment().combineTargets(null, false); if (!targets.isEmpty()) { targets.remove(0); } if (targets.size() != 1) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Exactly one file argument required"), SVNLogType.CLIENT); } SVNPath target = new SVNPath((String) targets.get(0)); if (!target.isFile()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Exactly one file argument required"), SVNLogType.CLIENT); } SVNPropertyValue propertyValue = SVNPropertyValue.create(SVNRevisionProperty.LOG, getEnvironment().readFromFile(target.getFile())); SVNURL url = SVNURL.fromFile(repos); FSRepository repository = (FSRepository) SVNRepositoryFactory.create(url); long rev = getRevisionNumber(getSVNAdminEnvironment().getStartRevision(), repository.getLatestRevision(), repository); repository.setRevisionPropertyValue(rev, SVNRevisionProperty.LOG, propertyValue, getSVNAdminEnvironment().isBypassHooks()); } } SVNAdminSetRevPropCommand.java000066400000000000000000000070551177510526000342000ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.io.File; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminSetRevPropCommand extends SVNAdminCommand { public SVNAdminSetRevPropCommand() { super("setrevprop", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNAdminOption.REVISION); options.add(SVNAdminOption.USE_PRE_REVPROP_CHANGE_HOOK); options.add(SVNAdminOption.USE_POST_REVPROP_CHANGE_HOOK); return options; } public void run() throws SVNException { if (getSVNAdminEnvironment().getStartRevision() == SVNRevision.UNDEFINED) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Missing revision"), SVNLogType.CLIENT); } if (getSVNAdminEnvironment().getEndRevision() != SVNRevision.UNDEFINED) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Only one revision allowed"), SVNLogType.CLIENT); } File repos = getLocalRepository(); List targets = getEnvironment().combineTargets(null, false); if (!targets.isEmpty()) { targets.remove(0); } if (targets.size() != 2) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Exactly one property name and one file argument required"), SVNLogType.CLIENT); } String propertyName = (String) targets.get(0); SVNPath target = new SVNPath((String) targets.get(1)); if (!target.isFile()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Exactly one property name and one file argument required"), SVNLogType.CLIENT); } SVNPropertyValue propertyValue = SVNPropertyValue.create(propertyName, getEnvironment().readFromFile(target.getFile())); SVNURL url = SVNURL.fromFile(repos); FSRepository repository = (FSRepository) SVNRepositoryFactory.create(url); long rev = getRevisionNumber(getSVNAdminEnvironment().getStartRevision(), repository.getLatestRevision(), repository); repository.setRevisionPropertyValue(rev, propertyName, propertyValue, !getSVNAdminEnvironment().isUsePreRevPropChangeHook(), !getSVNAdminEnvironment().isUsePostRevPropChangeHook()); } } SVNAdminSetUUIDCommand.java000066400000000000000000000033171177510526000333460ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminSetUUIDCommand extends SVNAdminCommand { public SVNAdminSetUUIDCommand() { super("setuuid", null); } protected Collection createSupportedOptions() { return null; } public void run() throws SVNException { String uuid = null; if (getEnvironment().getArguments().size() > 2) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR); SVNErrorManager.error(err, SVNLogType.CLIENT); } else if (getEnvironment().getArguments().size() > 1) { uuid = (String) getEnvironment().getArguments().get(1); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.doSetUUID(getLocalRepository(), uuid); } } SVNAdminUpgradeCommand.java000066400000000000000000000041421177510526000335100ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminUpgradeCommand extends SVNAdminCommand implements ISVNAdminEventHandler { public SVNAdminUpgradeCommand() { super("upgrade", null); } protected Collection createSupportedOptions() { return null; } public void run() throws SVNException { SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.doUpgrade(getLocalRepository()); getEnvironment().getOut().println(); getEnvironment().getOut().println("Upgrade completed."); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.UPGRADE) { getEnvironment().getOut().println("Repository lock acquired."); getEnvironment().getOut().println("Please wait; upgrading the repository may take some time..."); } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnadmin/SVNAdminVerifyCommand.java000066400000000000000000000067311177510526000334520ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnadmin; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNAdminVerifyCommand extends SVNAdminCommand implements ISVNAdminEventHandler { public SVNAdminVerifyCommand() { super("verify", null); } protected Collection createSupportedOptions() { Collection options = new LinkedList(); options.add(SVNAdminOption.REVISION); options.add(SVNAdminOption.QUIET); return options; } public void run() throws SVNException { SVNRevision start = getSVNAdminEnvironment().getStartRevision(); SVNRevision end = getSVNAdminEnvironment().getEndRevision(); SVNRepository repository = SVNRepositoryFactory.create(SVNURL.fromFile(getLocalRepository())); repository.setCanceller(getEnvironment()); long latestRevision = repository.getLatestRevision(); long startRev = getRevisionNumber(start, latestRevision, repository); long endRev = getRevisionNumber(end, latestRevision, repository); if (startRev < 0) { startRev = 0; endRev = latestRevision; } else if (endRev < 0) { endRev = startRev; } if (startRev > endRev) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "First revision cannot be higher than second"), SVNLogType.CLIENT); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); if (!getSVNAdminEnvironment().isQuiet()) { client.setEventHandler(this); } client.doVerify(getLocalRepository(), SVNRevision.create(startRev), SVNRevision.create(endRev)); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event != null && event.getAction() == SVNAdminEventAction.REVISION_DUMPED) { getEnvironment().getErr().println(event.getMessage()); } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { getEnvironment().checkCancelled(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/000077500000000000000000000000001177510526000275605ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/SVNDumpFilter.java000066400000000000000000000045211177510526000330670ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svndumpfilter; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNLauncher; import org.tmatesoft.svn.cli.SVNCommandLine; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDumpFilter extends AbstractSVNLauncher { public static void main(String[] args) { new SVNDumpFilter().run(args); } protected AbstractSVNCommandEnvironment createCommandEnvironment() { return new SVNDumpFilterCommandEnvironment(getProgramName(), System.out, System.err, System.in); } protected String getProgramName() { return "jsvndumpfilter"; } protected boolean needArgs() { return true; } protected boolean needCommand() { return true; } protected void registerCommands() { AbstractSVNCommand.registerCommand(new SVNDumpFilterHelpCommand()); AbstractSVNCommand.registerCommand(new SVNDumpFilterExcludeCommand()); AbstractSVNCommand.registerCommand(new SVNDumpFilterIncludeCommand()); } protected void registerOptions() { SVNCommandLine.registerOption(SVNDumpFilterOption.HELP); SVNCommandLine.registerOption(SVNDumpFilterOption.QUESTION); SVNCommandLine.registerOption(SVNDumpFilterOption.QUIET); SVNCommandLine.registerOption(SVNDumpFilterOption.VERSION); SVNCommandLine.registerOption(SVNDumpFilterOption.DROP_EMPTY_REVISIONS); SVNCommandLine.registerOption(SVNDumpFilterOption.PRESERVE_REVISION_PROPERTIES); SVNCommandLine.registerOption(SVNDumpFilterOption.RENUMBER_REVISIONS); SVNCommandLine.registerOption(SVNDumpFilterOption.SKIP_MISSING_MERGE_SOURCES); SVNCommandLine.registerOption(SVNDumpFilterOption.TARGETS); } } SVNDumpFilterCommand.java000066400000000000000000000037101177510526000343060ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svndumpfilter; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import org.tmatesoft.svn.cli.AbstractSVNCommand; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class SVNDumpFilterCommand extends AbstractSVNCommand { private int myOutputPriority; public SVNDumpFilterCommand(String name, String[] aliases, int outputPriority) { super(name, aliases); myOutputPriority = outputPriority; } public Collection getGlobalOptions() { return Collections.EMPTY_LIST; } protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNDumpFilterOption.DROP_EMPTY_REVISIONS); options.add(SVNDumpFilterOption.RENUMBER_REVISIONS); options.add(SVNDumpFilterOption.SKIP_MISSING_MERGE_SOURCES); options.add(SVNDumpFilterOption.TARGETS); options.add(SVNDumpFilterOption.PRESERVE_REVISION_PROPERTIES); options.add(SVNDumpFilterOption.QUIET); return options; } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svndumpfilter.commands"; } protected SVNDumpFilterCommandEnvironment getSVNDumpFilterEnvironment() { return (SVNDumpFilterCommandEnvironment) getEnvironment(); } public int getOutputPriority() { return myOutputPriority; } } SVNDumpFilterCommandEnvironment.java000066400000000000000000000166661177510526000365510ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svndumpfilter; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNOption; import org.tmatesoft.svn.cli.SVNCommandLine; import org.tmatesoft.svn.cli.SVNOptionValue; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDumpFilterCommandEnvironment extends AbstractSVNCommandEnvironment { private boolean myIsVersion; private boolean myIsQuiet; private boolean myIsHelp; private boolean myIsDropEmptyRevisions; private boolean myIsRenumberRevisions; private boolean myIsPreserveRevisionProperties; private boolean myIsSkipMissingMergeSources; private List myPrefixes; private String myTargetsFile; public boolean isVersion() { return myIsVersion; } public boolean isQuiet() { return myIsQuiet; } public boolean isHelp() { return myIsHelp; } public boolean isDropEmptyRevisions() { return myIsDropEmptyRevisions; } public boolean isRenumberRevisions() { return myIsRenumberRevisions; } public boolean isPreserveRevisionProperties() { return myIsPreserveRevisionProperties; } public boolean isSkipMissingMergeSources() { return myIsSkipMissingMergeSources; } public List getPrefixes() { return myPrefixes; } public SVNDumpFilterCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { super(programName, out, err, in); } protected ISVNAuthenticationManager createClientAuthenticationManager() { return null; } protected DefaultSVNOptions createClientOptions() throws SVNException { return null; } protected void initOptions(SVNCommandLine commandLine) throws SVNException { super.initOptions(commandLine); if (getCommand().getClass() == SVNDumpFilterHelpCommand.class) { return; } List arguments = getArguments(); myPrefixes = new LinkedList(); if (arguments != null) { for (Iterator prefixesIter = arguments.iterator(); prefixesIter.hasNext();) { String prefix = (String) prefixesIter.next(); prefix = prefix.replace(File.separatorChar, '/'); prefix = SVNPathUtil.canonicalizePath(prefix); if (!prefix.startsWith("/")) { prefix = "/" + prefix; } myPrefixes.add(prefix); } } if (myTargetsFile != null) { File targetsFile = new File(myTargetsFile); String contents = new String(readFromFile(targetsFile)); for (StringTokenizer tokens = new StringTokenizer(contents, "\n\r"); tokens.hasMoreTokens();) { String prefix = tokens.nextToken(); myPrefixes.add(prefix); } } if (myPrefixes.isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Error: no prefixes supplied."); SVNErrorManager.error(err, SVNLogType.CLIENT); } } protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNDumpFilterOption.DROP_EMPTY_REVISIONS) { myIsDropEmptyRevisions = true; } else if (option == SVNDumpFilterOption.RENUMBER_REVISIONS) { myIsRenumberRevisions = true; } else if (option == SVNDumpFilterOption.PRESERVE_REVISION_PROPERTIES) { myIsPreserveRevisionProperties = true; } else if (option == SVNDumpFilterOption.SKIP_MISSING_MERGE_SOURCES) { myIsSkipMissingMergeSources = true; } else if (option == SVNDumpFilterOption.VERSION) { myIsVersion = true; } else if (option == SVNDumpFilterOption.QUIET) { myIsQuiet = true; } else if (option == SVNDumpFilterOption.TARGETS) { myTargetsFile = optionValue.getValue(); } else if (option == SVNDumpFilterOption.HELP || option == SVNDumpFilterOption.QUESTION) { myIsHelp = true; } } protected String refineCommandName(String commandName, SVNCommandLine commandLine) throws SVNException { for (Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); AbstractSVNOption option = optionValue.getOption(); if (option == SVNDumpFilterOption.HELP || option == SVNDumpFilterOption.QUESTION) { myIsHelp = true; } else if (option == SVNDumpFilterOption.VERSION) { myIsVersion = true; } } if (myIsHelp) { List newArguments = commandName != null ? Collections.singletonList(commandName) : Collections.EMPTY_LIST; setArguments(newArguments); return "help"; } if (commandName == null) { if (isVersion()) { SVNDumpFilterCommand versionCommand = new SVNDumpFilterCommand("--version", null, 0) { protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNDumpFilterOption.VERSION); return options; } public void run() throws SVNException { AbstractSVNCommand helpCommand = AbstractSVNCommand.getCommand("help"); helpCommand.init(SVNDumpFilterCommandEnvironment.this); helpCommand.run(); } }; AbstractSVNCommand.registerCommand(versionCommand); return "--version"; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Subcommand argument required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return commandName; } protected String getCommandLineClientName() { return "svndumpfilter"; } } SVNDumpFilterExcludeCommand.java000066400000000000000000000107461177510526000356270ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svndumpfilter; import java.util.Iterator; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDumpFilterExcludeCommand extends SVNDumpFilterCommand implements ISVNAdminEventHandler { private boolean myHasPrintedRenumberedRevisionsHeader; private boolean myIsPrintFinalEOL; public SVNDumpFilterExcludeCommand() { super("exclude", null, 0); } public void run() throws SVNException { SVNDumpFilterCommandEnvironment environment = getSVNDumpFilterEnvironment(); if (!environment.isQuiet()) { if (environment.isDropEmptyRevisions()) { environment.getErr().println("Excluding (and dropping empty revisions for) prefixes:"); } else { environment.getErr().println("Excluding prefixes:"); } for (Iterator prefixesIter = environment.getPrefixes().iterator(); prefixesIter.hasNext();) { String prefix = (String) prefixesIter.next(); environment.getErr().println(" '" + prefix + "'"); } environment.getErr().println(); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.doFilter(environment.getIn(), environment.getOut(), true, environment.isRenumberRevisions(), environment.isDropEmptyRevisions(), environment.isPreserveRevisionProperties(), environment.getPrefixes(), environment.isSkipMissingMergeSources()); if (!environment.isQuiet() && myIsPrintFinalEOL) { environment.getErr().println(); } } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { SVNDumpFilterCommandEnvironment environment = getSVNDumpFilterEnvironment(); if (!environment.isQuiet()) { SVNAdminEventAction action = event.getAction(); if (action == SVNAdminEventAction.DUMP_FILTER_REVISION_COMMITTED || action == SVNAdminEventAction.DUMP_FILTER_REVISION_SKIPPED) { environment.getErr().println(event.getMessage()); } else if (action == SVNAdminEventAction.DUMP_FILTER_TOTAL_REVISIONS_DROPPED) { environment.getErr().println(); environment.getErr().println(event.getMessage()); environment.getErr().println(); environment.getErr().println(); } else if (action == SVNAdminEventAction.DUMP_FILTER_RENUMBERED_REVISION || action == SVNAdminEventAction.DUMP_FILTER_DROPPED_RENUMBERED_REVISION) { if (!myHasPrintedRenumberedRevisionsHeader) { environment.getErr().println("Revisions renumbered as follows:"); myHasPrintedRenumberedRevisionsHeader = true; } environment.getErr().println(" " + event.getMessage()); } else if (action == SVNAdminEventAction.DUMP_FILTER_TOTAL_NODES_DROPPED) { if (myHasPrintedRenumberedRevisionsHeader) { environment.getErr().println(); } environment.getErr().println(event.getMessage()); myIsPrintFinalEOL = true; } else if (action == SVNAdminEventAction.DUMP_FILTER_DROPPED_NODE) { environment.getErr().println(" " + event.getMessage()); } } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { } } SVNDumpFilterHelpCommand.java000066400000000000000000000075611177510526000351270ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svndumpfilter; import java.text.MessageFormat; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Comparator; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDumpFilterHelpCommand extends SVNDumpFilterCommand { private static final String GENERIC_HELP_HEADER = "general usage: {0} SUBCOMMAND [ARGS & OPTIONS ...]\n" + "Type ''{0} help '' for help on a specific subcommand.\n" + "Type ''{0} --version'' to see the program version.\n" + "\n" + "Available subcommands:"; public SVNDumpFilterHelpCommand() { super("help", new String[] {"?", "h"}, 1); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { if (!getEnvironment().getArguments().isEmpty()) { for (Iterator commands = getEnvironment().getArguments().iterator(); commands.hasNext();) { String commandName = (String) commands.next(); AbstractSVNCommand command = AbstractSVNCommand.getCommand(commandName); if (command == null) { getEnvironment().getErr().println("\"" + commandName + "\": unknown command.\n"); continue; } String help = SVNCommandUtil.getCommandHelp(command, getEnvironment().getProgramName(), false); getEnvironment().getOut().println(help); } } else if (getSVNDumpFilterEnvironment().isVersion()) { String version = SVNCommandUtil.getVersion(getEnvironment(), getSVNDumpFilterEnvironment().isQuiet()); getEnvironment().getOut().println(version); } else if (getEnvironment().getArguments().isEmpty()) { Comparator commandComparator = new Comparator() { public int compare(Object o1, Object o2) { AbstractSVNCommand c1 = (AbstractSVNCommand) o1; AbstractSVNCommand c2 = (AbstractSVNCommand) o2; if (c1 instanceof SVNDumpFilterCommand && c2 instanceof SVNDumpFilterCommand) { SVNDumpFilterCommand dumpFilterCommand1 = (SVNDumpFilterCommand) c1; SVNDumpFilterCommand dumpFilterCommand2 = (SVNDumpFilterCommand) c2; if (dumpFilterCommand1.getOutputPriority() != dumpFilterCommand2.getOutputPriority()) { return dumpFilterCommand1.getOutputPriority() < dumpFilterCommand2.getOutputPriority() ? -1 : 1; } } return c1.getName().compareTo(c2.getName()); } }; String help = SVNCommandUtil.getGenericHelp(getEnvironment().getProgramName(), GENERIC_HELP_HEADER, null, commandComparator); getEnvironment().getOut().print(help); } else { String message = MessageFormat.format("Type ''{0} help'' for usage.", new Object[] { getEnvironment().getProgramName() }); getEnvironment().getOut().println(message); } } } SVNDumpFilterIncludeCommand.java000066400000000000000000000107471177510526000356220ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svndumpfilter; import java.util.Iterator; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDumpFilterIncludeCommand extends SVNDumpFilterCommand implements ISVNAdminEventHandler { private boolean myHasPrintedRenumberedRevisionsHeader; private boolean myIsPrintFinalEOL; public SVNDumpFilterIncludeCommand() { super("include", null, 0); } public void run() throws SVNException { SVNDumpFilterCommandEnvironment environment = getSVNDumpFilterEnvironment(); if (!environment.isQuiet()) { if (environment.isDropEmptyRevisions()) { environment.getErr().println("Including (and dropping empty revisions for) prefixes:"); } else { environment.getErr().println("Including prefixes:"); } for (Iterator prefixesIter = environment.getPrefixes().iterator(); prefixesIter.hasNext();) { String prefix = (String) prefixesIter.next(); environment.getErr().println(" '" + prefix + "'"); } environment.getErr().println(); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.doFilter(environment.getIn(), environment.getOut(), false, environment.isRenumberRevisions(), environment.isDropEmptyRevisions(), environment.isPreserveRevisionProperties(), environment.getPrefixes(), environment.isSkipMissingMergeSources()); if (!environment.isQuiet() && myIsPrintFinalEOL) { environment.getErr().println(); } } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { SVNDumpFilterCommandEnvironment environment = getSVNDumpFilterEnvironment(); if (!environment.isQuiet()) { SVNAdminEventAction action = event.getAction(); if (action == SVNAdminEventAction.DUMP_FILTER_REVISION_COMMITTED || action == SVNAdminEventAction.DUMP_FILTER_REVISION_SKIPPED) { environment.getErr().println(event.getMessage()); } else if (action == SVNAdminEventAction.DUMP_FILTER_TOTAL_REVISIONS_DROPPED) { environment.getErr().println(); environment.getErr().println(event.getMessage()); environment.getErr().println(); environment.getErr().println(); } else if (action == SVNAdminEventAction.DUMP_FILTER_RENUMBERED_REVISION || action == SVNAdminEventAction.DUMP_FILTER_DROPPED_RENUMBERED_REVISION) { if (!myHasPrintedRenumberedRevisionsHeader) { environment.getErr().println("Revisions renumbered as follows:"); myHasPrintedRenumberedRevisionsHeader = true; } environment.getErr().println(" " + event.getMessage()); } else if (action == SVNAdminEventAction.DUMP_FILTER_TOTAL_NODES_DROPPED) { if (myHasPrintedRenumberedRevisionsHeader) { environment.getErr().println(); } environment.getErr().println(event.getMessage()); myIsPrintFinalEOL = true; } else if (action == SVNAdminEventAction.DUMP_FILTER_DROPPED_NODE) { environment.getErr().println(" " + event.getMessage()); } } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { } } SVNDumpFilterOption.java000066400000000000000000000037151177510526000342050ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svndumpfilter/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svndumpfilter; import org.tmatesoft.svn.cli.AbstractSVNOption; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNDumpFilterOption extends AbstractSVNOption { public static final SVNDumpFilterOption HELP = new SVNDumpFilterOption("help", "h", true); public static final SVNDumpFilterOption QUESTION = new SVNDumpFilterOption("?", null, true); public static final SVNDumpFilterOption VERSION = new SVNDumpFilterOption("version", null, true); public static final SVNDumpFilterOption QUIET = new SVNDumpFilterOption("quiet", "q", true); public static final SVNDumpFilterOption DROP_EMPTY_REVISIONS = new SVNDumpFilterOption("drop-empty-revs", null, true); public static final SVNDumpFilterOption RENUMBER_REVISIONS = new SVNDumpFilterOption("renumber-revs", null, true); public static final SVNDumpFilterOption SKIP_MISSING_MERGE_SOURCES = new SVNDumpFilterOption("skip-missing-merge-sources", null, true); public static final SVNDumpFilterOption PRESERVE_REVISION_PROPERTIES = new SVNDumpFilterOption("preserve-revprops", null, true); public static final SVNDumpFilterOption TARGETS = new SVNDumpFilterOption("targets", null, false); private SVNDumpFilterOption(String name, String alias, boolean unary) { super(name, alias, unary); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svndumpfilter.options"; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/000077500000000000000000000000001177510526000263515ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLook.java000066400000000000000000000070401177510526000305100ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNLauncher; import org.tmatesoft.svn.cli.SVNCommandLine; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLook extends AbstractSVNLauncher { public static void main(String[] args) { new SVNLook().run(args); } protected AbstractSVNCommandEnvironment createCommandEnvironment() { return new SVNLookCommandEnvironment(getProgramName(), System.out, System.err, System.in); } protected String getProgramName() { return "jsvnlook"; } protected boolean needArgs() { return true; } protected boolean needCommand() { return true; } protected void registerCommands() { AbstractSVNCommand.registerCommand(new SVNLookAuthorCommand()); AbstractSVNCommand.registerCommand(new SVNLookDateCommand()); AbstractSVNCommand.registerCommand(new SVNLookLogCommand()); AbstractSVNCommand.registerCommand(new SVNLookUUIDCommand()); AbstractSVNCommand.registerCommand(new SVNLookYoungestCommand()); AbstractSVNCommand.registerCommand(new SVNLookHelpCommand()); AbstractSVNCommand.registerCommand(new SVNLookTreeCommand()); AbstractSVNCommand.registerCommand(new SVNLookPropGetCommand()); AbstractSVNCommand.registerCommand(new SVNLookPropListCommand()); AbstractSVNCommand.registerCommand(new SVNLookDirsChangedCommand()); AbstractSVNCommand.registerCommand(new SVNLookDiffCommand()); AbstractSVNCommand.registerCommand(new SVNLookInfoCommand()); AbstractSVNCommand.registerCommand(new SVNLookChangedCommand()); AbstractSVNCommand.registerCommand(new SVNLookHistoryCommand()); AbstractSVNCommand.registerCommand(new SVNLookCatCommand()); AbstractSVNCommand.registerCommand(new SVNLookLockCommand()); } protected void registerOptions() { SVNCommandLine.registerOption(SVNLookOption.HELP); SVNCommandLine.registerOption(SVNLookOption.QUESTION); SVNCommandLine.registerOption(SVNLookOption.VERSION); SVNCommandLine.registerOption(SVNLookOption.COPY_INFO); SVNCommandLine.registerOption(SVNLookOption.DIFF_COPY_FROM); SVNCommandLine.registerOption(SVNLookOption.FULL_PATHS); SVNCommandLine.registerOption(SVNLookOption.LIMIT); SVNCommandLine.registerOption(SVNLookOption.NO_DIFF_ADDED); SVNCommandLine.registerOption(SVNLookOption.NO_DIFF_DELETED); SVNCommandLine.registerOption(SVNLookOption.NON_RECURSIVE); SVNCommandLine.registerOption(SVNLookOption.REVISION); SVNCommandLine.registerOption(SVNLookOption.REVPROP); SVNCommandLine.registerOption(SVNLookOption.SHOW_IDS); SVNCommandLine.registerOption(SVNLookOption.TRANSACTION); SVNCommandLine.registerOption(SVNLookOption.VERBOSE); SVNCommandLine.registerOption(SVNLookOption.EXTENSIONS); } }svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookAuthorCommand.java000066400000000000000000000031201177510526000331650ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookAuthorCommand extends SVNLookCommand { protected SVNLookAuthorCommand() { super("author", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); return options; } public void run() throws SVNException { SVNProperties props = getProperties(); SVNPropertyValue value = props.getSVNPropertyValue(SVNRevisionProperty.AUTHOR); if (value != null && value.getString() != null) { getEnvironment().getOut().print(value.getString()); } getEnvironment().getOut().println(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookCatCommand.java000066400000000000000000000041751177510526000324450ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.1.2 * @author TMate Software Ltd. */ public class SVNLookCatCommand extends SVNLookCommand { protected SVNLookCatCommand() { super("cat", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); String path = environment.getFirstArgument(); if (environment.getFirstArgument() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Missing repository path argument"); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNLookClient client = environment.getClientManager().getLookClient(); if (environment.isRevision()) { client.doCat(environment.getRepositoryFile(), path, getRevisionObject(), environment.getOut()); } else { client.doCat(environment.getRepositoryFile(), path, environment.getTransaction(), environment.getOut()); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookChangedCommand.java000066400000000000000000000062721177510526000332670ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.wc.admin.ISVNChangeEntryHandler; import org.tmatesoft.svn.core.wc.admin.SVNChangeEntry; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookChangedCommand extends SVNLookCommand implements ISVNChangeEntryHandler { public SVNLookChangedCommand() { super("changed", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); options.add(SVNLookOption.COPY_INFO); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); SVNLookClient client = environment.getClientManager().getLookClient(); if (environment.isRevision()) { client.doGetChanged(environment.getRepositoryFile(), getRevisionObject(), this, environment.isCopyInfo()); } else { client.doGetChanged(environment.getRepositoryFile(), environment.getTransaction(), this, environment.isCopyInfo()); } } public void handleEntry(SVNChangeEntry entry) throws SVNException { String[] status = new String[3]; status[0] = entry.getType() == SVNChangeEntry.TYPE_UPDATED && !entry.hasTextModifications() ? "_" : "" + entry.getType(); status[1] = entry.hasPropertyModifications() ? "" + SVNChangeEntry.TYPE_UPDATED : " "; status[2] = entry.getCopyFromPath() != null ? "+" : " "; String path = !entry.getPath().endsWith("/") && entry.getKind() == SVNNodeKind.DIR ? entry.getPath() + "/" : entry.getPath(); path = path.startsWith("/") ? path.substring(1) : path; SVNLookCommandEnvironment environment = getSVNLookEnvironment(); environment.getOut().println(status[0] + status[1] + status[2] + " " + path); if (entry.getCopyFromPath() != null) { String copyFromPath = entry.getCopyFromPath(); if (copyFromPath.startsWith("/")) { copyFromPath = copyFromPath.substring(1); } if (!copyFromPath.endsWith("/") && entry.getKind() == SVNNodeKind.DIR) { copyFromPath += "/"; } environment.getOut().println(" (from " + copyFromPath + ":r" + entry.getCopyFromRevision() + ")"); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookCommand.java000066400000000000000000000052071177510526000320120ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.Collections; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionRoot; import org.tmatesoft.svn.core.wc.SVNRevision; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class SVNLookCommand extends AbstractSVNCommand { public SVNLookCommand(String name, String[] aliases) { super(name, aliases); } public Collection getGlobalOptions() { return Collections.EMPTY_LIST; } protected SVNLookCommandEnvironment getSVNLookEnvironment() { return (SVNLookCommandEnvironment) getEnvironment(); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnlook.commands"; } protected FSRoot getFSRoot() throws SVNException { FSRepository repository = getSVNLookEnvironment().getRepository(); if (getSVNLookEnvironment().isRevision()) { long rev = getSVNLookEnvironment().getRevision(); if (rev < 0) { rev = repository.getLatestRevision(); } return repository.getFSFS().createRevisionRoot(rev); } return repository.getFSFS().createTransactionRoot(getSVNLookEnvironment().getTransactionInfo()); } protected SVNProperties getProperties() throws SVNException { FSRoot root = getFSRoot(); if (root instanceof FSTransactionRoot) { return root.getOwner().getTransactionProperties(((FSTransactionRoot) root).getTxnID()); } return root.getOwner().getRevisionProperties(root.getRevision()); } protected SVNRevision getRevisionObject() { if (!SVNRevision.isValidRevisionNumber(getSVNLookEnvironment().getRevision())) { return SVNRevision.HEAD; } return SVNRevision.create(getSVNLookEnvironment().getRevision()); } } SVNLookCommandEnvironment.java000066400000000000000000000313661177510526000341650ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNOption; import org.tmatesoft.svn.cli.SVNCommandLine; import org.tmatesoft.svn.cli.SVNOptionValue; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.util.SVNHashSet; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.SVNDiffOptions; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookCommandEnvironment extends AbstractSVNCommandEnvironment { private long myRevision; private String myTransaction; private boolean myIsNonRecursive; private boolean myIsVerbose; private boolean myIsHelp; private boolean myIsRevProp; private boolean myIsVersion; private boolean myIsShowIDs; private long myLimit; private boolean myIsNoDiffDeleted; private boolean myIsNoDiffAdded; private boolean myIsDiffCopyFrom; private boolean myIsFullPaths; private boolean myIsCopyInfo; private Collection myExtensions; private boolean myIsRevision; private File myRepositoryFile; private FSRepository myRepository; private FSTransactionInfo myTransactionInfo; private String myArgument1; private String myArgument2; public SVNLookCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { super(programName, out, err, in); myRevision = -1; myExtensions = new SVNHashSet(); } public File getRepositoryFile() { return myRepositoryFile; } public long getRevision() { return myRevision; } public String getTransaction() { return myTransaction; } public boolean isNonRecursive() { return myIsNonRecursive; } public boolean isVerbose() { return myIsVerbose; } public boolean isHelp() { return myIsHelp; } public boolean isRevProp() { return myIsRevProp; } public boolean isVersion() { return myIsVersion; } public boolean isShowIDs() { return myIsShowIDs; } public long getLimit() { return myLimit; } public boolean isNoDiffDeleted() { return myIsNoDiffDeleted; } public boolean isNoDiffAdded() { return myIsNoDiffAdded; } public boolean isDiffCopyFrom() { return myIsDiffCopyFrom; } public boolean isFullPaths() { return myIsFullPaths; } public boolean isCopyInfo() { return myIsCopyInfo; } public Collection getExtensions() { return myExtensions; } public boolean isRevision() { return myIsRevision; } public FSTransactionInfo getTransactionInfo() { return myTransactionInfo; } public FSRepository getRepository() { return myRepository; } public String getFirstArgument() { return myArgument1; } public String getSecondArgument() { return myArgument2; } protected ISVNAuthenticationManager createClientAuthenticationManager() { return SVNWCUtil.createDefaultAuthenticationManager(); } protected DefaultSVNOptions createClientOptions() { return SVNWCUtil.createDefaultOptions(true); } protected void validateOptions(SVNCommandLine commandLine) throws SVNException { super.validateOptions(commandLine); if (myRevision >= 0 && myTransaction != null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS, "The '--transaction' (-t) and '--revision' (-r) arguments can not co-exist"); SVNErrorManager.error(err, SVNLogType.CLIENT); } myIsRevision = myTransaction == null; if (!(myIsHelp || myIsVersion || "help".equals(commandLine.getCommandName()))) { if (getArguments().isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Repository argument required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPath path = new SVNPath((String) getArguments().get(0), false); if (path.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is URL when it should be a path", path.getTarget()); SVNErrorManager.error(err, SVNLogType.CLIENT); } myRepositoryFile = path.getFile(); myRepository = (FSRepository) SVNRepositoryFactory.create(SVNURL.fromFile(myRepositoryFile)); myRepository.setCanceller(this); myRepository.testConnection(); if (getTransaction() != null) { myTransactionInfo = myRepository.getFSFS().openTxn(getTransaction()); } else { if (myRevision < 0) { myRevision = myRepository.getLatestRevision(); } } List updatedArguments = new LinkedList(getArguments()); updatedArguments.remove(0); if (!updatedArguments.isEmpty()) { myArgument1 = (String) updatedArguments.remove(0); } if (!updatedArguments.isEmpty()) { myArgument2 = (String) updatedArguments.remove(0); } setArguments(updatedArguments); } } protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNLookOption.REVISION) { long revision = -1; if (optionValue.getValue() != null) { try { revision = Long.parseLong(optionValue.getValue()); } catch (NumberFormatException nfe) { } } if (revision < 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Invalid revision number supplied"); SVNErrorManager.error(err, SVNLogType.CLIENT); } myRevision = revision; } else if (option == SVNLookOption.TRANSACTION) { myTransaction = optionValue.getValue(); } else if (option == SVNLookOption.NON_RECURSIVE) { myIsNonRecursive = true; } else if (option == SVNLookOption.VERBOSE) { myIsVerbose = true; } else if (option == SVNLookOption.HELP || option == SVNLookOption.QUESTION) { myIsHelp = true; } else if (option == SVNLookOption.REVPROP) { myIsRevProp = true; } else if (option == SVNLookOption.VERSION) { myIsVersion = true; } else if (option == SVNLookOption.SHOW_IDS) { myIsShowIDs = true; } else if (option == SVNLookOption.LIMIT) { long limit = -1; if (optionValue.getValue() != null) { try { limit = Long.parseLong(optionValue.getValue()); } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric limit argument given"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Non-numeric limit argument given"); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (limit <= 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Argument to --limit must be positive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } myLimit = limit; } else if (option == SVNLookOption.NO_DIFF_DELETED) { myIsNoDiffDeleted = true; } else if (option == SVNLookOption.NO_DIFF_ADDED) { myIsNoDiffAdded = true; } else if (option == SVNLookOption.DIFF_COPY_FROM) { myIsDiffCopyFrom = true; } else if (option == SVNLookOption.FULL_PATHS) { myIsFullPaths = true; } else if (option == SVNLookOption.COPY_INFO) { myIsCopyInfo = true; } else if (option == SVNLookOption.EXTENSIONS) { myExtensions.add(optionValue.getValue()); } } public SVNDiffOptions getDiffOptions() throws SVNException { LinkedList extensions = new LinkedList(myExtensions); boolean ignoreAllWS = myExtensions.contains("-w") || myExtensions.contains("--ignore-all-space"); if (ignoreAllWS) { extensions.remove("-w"); extensions.remove("--ignore-all-space"); } boolean ignoreAmountOfWS = myExtensions.contains("-b") || myExtensions.contains("--ignore-space-change"); if (ignoreAmountOfWS) { extensions.remove("-b"); extensions.remove("--ignore-space-change"); } boolean ignoreEOLStyle = myExtensions.contains("--ignore-eol-style"); if (ignoreEOLStyle) { extensions.remove("--ignore-eol-style"); } if (!extensions.isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INVALID_DIFF_OPTION, "Invalid argument ''{0}'' in diff options", extensions.get(0)); SVNErrorManager.error(err, SVNLogType.CLIENT); } return new SVNDiffOptions(ignoreAllWS, ignoreAmountOfWS, ignoreEOLStyle); } protected String refineCommandName(String commandName, SVNCommandLine commandLine) throws SVNException { for (Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); AbstractSVNOption option = optionValue.getOption(); if (option == SVNLookOption.HELP || option == SVNLookOption.QUESTION) { myIsHelp = true; } else if (option == SVNLookOption.VERSION) { myIsVersion = true; } } if (myIsHelp) { List newArguments = commandName != null ? Collections.singletonList(commandName) : Collections.EMPTY_LIST; setArguments(newArguments); return "help"; } if (commandName == null) { if (myIsVersion) { SVNLookCommand versionCommand = new SVNLookCommand("--version", null) { protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNLookOption.VERSION); return options; } public void run() throws SVNException { AbstractSVNCommand helpCommand = AbstractSVNCommand.getCommand("help"); helpCommand.init(SVNLookCommandEnvironment.this); helpCommand.run(); } }; AbstractSVNCommand.registerCommand(versionCommand); return "--version"; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Subcommand argument required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return commandName; } protected String getCommandLineClientName() { return "svnlook"; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookDateCommand.java000066400000000000000000000033211177510526000326030ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.util.SVNDate; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookDateCommand extends SVNLookCommand { protected SVNLookDateCommand() { super("date", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); return options; } public void run() throws SVNException { SVNProperties props = getProperties(); SVNPropertyValue value = props.getSVNPropertyValue(SVNRevisionProperty.DATE); if (value != null && value.getString() != null) { SVNDate date = SVNDate.parseDate(value.getString()); getEnvironment().getOut().print(SVNDate.formatHumanDate(date, null)); } getEnvironment().getOut().println(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookDiffCommand.java000066400000000000000000000046661177510526000326130ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.DefaultSVNGNUDiffGenerator; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookDiffCommand extends SVNLookCommand { public SVNLookDiffCommand() { super("diff", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); options.add(SVNLookOption.NO_DIFF_DELETED); options.add(SVNLookOption.NO_DIFF_ADDED); options.add(SVNLookOption.DIFF_COPY_FROM); options.add(SVNLookOption.EXTENSIONS); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); SVNLookClient client = environment.getClientManager().getLookClient(); DefaultSVNGNUDiffGenerator defaultDiffGenerator = new DefaultSVNGNUDiffGenerator(); defaultDiffGenerator.setOptions(client.getOptions()); defaultDiffGenerator.setDiffOptions(environment.getDiffOptions()); client.setDiffGenerator(defaultDiffGenerator); if (environment.isRevision()) { client.doGetDiff(environment.getRepositoryFile(), getRevisionObject(), !environment.isNoDiffDeleted(), !environment.isNoDiffAdded(), environment.isDiffCopyFrom(), environment.getOut()); } else { client.doGetDiff(environment.getRepositoryFile(), environment.getTransaction(), !environment.isNoDiffDeleted(), !environment.isNoDiffAdded(), environment.isDiffCopyFrom(), environment.getOut()); } } } SVNLookDirsChangedCommand.java000066400000000000000000000040371177510526000340270ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.admin.ISVNChangedDirectoriesHandler; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookDirsChangedCommand extends SVNLookCommand implements ISVNChangedDirectoriesHandler { public SVNLookDirsChangedCommand() { super("dirs-changed", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); SVNLookClient client = environment.getClientManager().getLookClient(); if (environment.isRevision()) { client.doGetChangedDirectories(environment.getRepositoryFile(), getRevisionObject(), this); } else { client.doGetChangedDirectories(environment.getRepositoryFile(), environment.getTransaction(), this); } } public void handleDir(String path) throws SVNException { if (path.startsWith("/")) { path = path.substring(1); } if (!path.endsWith("/")) { path += "/"; } getSVNLookEnvironment().getOut().println(path); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookHelpCommand.java000066400000000000000000000064371177510526000326310ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.text.MessageFormat; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookHelpCommand extends SVNLookCommand { private static final String GENERIC_HELP_HEADER = "general usage: {0} SUBCOMMAND REPOS_PATH [ARGS & OPTIONS ...]\n" + "Note: any subcommand which takes the ''--revision'' and ''--transaction''\n" + " options will, if invoked without one of those options, act on\n" + " the repository''s youngest revision.\n" + "Type ''{0} help '' for help on a specific subcommand.\n" + "Type ''{0} --version'' to see the program version and FS modules.\n" + "\n" + "Available subcommands:"; private static final String VERSION_HELP_FOOTER = "\nThe following repository back-end (FS) modules are available:\n\n" + "* fs_fs : Module for working with a plain file (FSFS) repository."; public SVNLookHelpCommand() { super("help", new String[] {"?", "h"}); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { if (!getEnvironment().getArguments().isEmpty()) { for (Iterator commands = getEnvironment().getArguments().iterator(); commands.hasNext();) { String commandName = (String) commands.next(); AbstractSVNCommand command = AbstractSVNCommand.getCommand(commandName); if (command == null) { getEnvironment().getErr().println("\"" + commandName + "\": unknown command.\n"); continue; } String help = SVNCommandUtil.getCommandHelp(command, getEnvironment().getProgramName(), true); getEnvironment().getOut().println(help); } } else if (getSVNLookEnvironment().isVersion()) { String version = SVNCommandUtil.getVersion(getEnvironment(), false); getEnvironment().getOut().println(version); getEnvironment().getOut().println(VERSION_HELP_FOOTER); } else if (getEnvironment().getArguments().isEmpty()) { String help = SVNCommandUtil.getGenericHelp(getEnvironment().getProgramName(), GENERIC_HELP_HEADER, null, null); getEnvironment().getOut().print(help); } else { String message = MessageFormat.format("Type ''{0} help'' for usage.", new Object[] {getEnvironment().getProgramName()}); getEnvironment().getOut().println(message); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookHistoryCommand.java000066400000000000000000000050241177510526000333710ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.admin.ISVNHistoryHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminPath; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookHistoryCommand extends SVNLookCommand implements ISVNHistoryHandler { public SVNLookHistoryCommand() { super("history", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.SHOW_IDS); options.add(SVNLookOption.LIMIT); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); if (environment.isShowIDs()) { environment.getOut().println("REVISION PATH "); environment.getOut().println("-------- ---------"); } else { environment.getOut().println("REVISION PATH"); environment.getOut().println("-------- ----"); } SVNLookClient client = environment.getClientManager().getLookClient(); client.doGetHistory(environment.getRepositoryFile(), environment.getFirstArgument(), getRevisionObject(), environment.isShowIDs(), environment.getLimit(), this); } public void handlePath(SVNAdminPath path) throws SVNException { if (path != null) { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); if (environment.isShowIDs()) { environment.getOut().println(path.getRevision() + " " + path.getPath() + " <" + path.getNodeID() + ">"); } else { environment.getOut().println(path.getRevision() + " " + path.getPath()); } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookInfoCommand.java000066400000000000000000000045241177510526000326270ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookInfoCommand extends SVNLookCommand { public SVNLookInfoCommand() { super("info", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); SVNLookClient client = environment.getClientManager().getLookClient(); SVNLogEntry logEntry = null; if (environment.isRevision()) { logEntry = client.doGetInfo(environment.getRepositoryFile(), getRevisionObject()); } else { logEntry = client.doGetInfo(environment.getRepositoryFile(), environment.getTransaction()); } String author = logEntry.getAuthor() != null ? logEntry.getAuthor() : ""; String date = logEntry.getDate() != null ? SVNDate.formatCustomDate(logEntry.getDate()) : ""; String log = logEntry.getMessage() != null ? logEntry.getMessage() : ""; environment.getOut().println(author); environment.getOut().println(date); if (log == null || log.length() == 0) { environment.getOut().println("0"); } else { environment.getOut().println(String.valueOf(log.length())); environment.getOut().println(log); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookLockCommand.java000066400000000000000000000064531177510526000326270ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.ISVNOptions; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.1.2 * @author TMate Software Ltd. */ public class SVNLookLockCommand extends SVNLookCommand { protected SVNLookLockCommand() { super("lock", null); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); String path = environment.getFirstArgument(); if (environment.getFirstArgument() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Missing path argument"); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNLookClient client = environment.getClientManager().getLookClient(); SVNLock lock = client.doGetLock(environment.getRepositoryFile(), path); if (lock != null) { ISVNOptions options = getEnvironment().getClientManager().getOptions(); String creationDate = SVNDate.formatHumanDate(lock.getCreationDate(), options); String expirationDate = lock.getExpirationDate() != null ? SVNDate.formatHumanDate(lock.getExpirationDate(), options) : ""; int commentLinesCount = lock.getComment() != null ? SVNCommandUtil.getLinesCount(lock.getComment()) : 0; getSVNLookEnvironment().getOut().println("UUID Token: " + lock.getID()); getSVNLookEnvironment().getOut().println("Owner: " + lock.getOwner()); getSVNLookEnvironment().getOut().println("Created: " + creationDate); getSVNLookEnvironment().getOut().println("Expires: " + expirationDate); String countMessage = "Comment (" + commentLinesCount + " "; String comment = lock.getComment() != null ? lock.getComment() : ""; if (commentLinesCount != 1) { getSVNLookEnvironment().getOut().println(countMessage + " lines):"); getSVNLookEnvironment().getOut().println(comment); } else { getSVNLookEnvironment().getOut().println(countMessage + "line):"); getSVNLookEnvironment().getOut().println(comment); } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookLogCommand.java000066400000000000000000000031041177510526000324460ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookLogCommand extends SVNLookCommand { protected SVNLookLogCommand() { super("log", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); return options; } public void run() throws SVNException { SVNProperties props = getProperties(); SVNPropertyValue value = props.getSVNPropertyValue(SVNRevisionProperty.LOG); if (value != null && value.getString() != null) { getEnvironment().getOut().print(value.getString()); } getEnvironment().getOut().println(); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookOption.java000066400000000000000000000047611177510526000317100ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import org.tmatesoft.svn.cli.AbstractSVNOption; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookOption extends AbstractSVNOption { public static final SVNLookOption HELP = new SVNLookOption("help", "h", true); public static final SVNLookOption QUESTION = new SVNLookOption("?", null, true); public static final SVNLookOption VERSION = new SVNLookOption("version", null, true); public static final SVNLookOption COPY_INFO = new SVNLookOption("copy-info", null, true); public static final SVNLookOption DIFF_COPY_FROM = new SVNLookOption("diff-copy-from", null, true); public static final SVNLookOption FULL_PATHS = new SVNLookOption("full-paths", null, true); public static final SVNLookOption LIMIT = new SVNLookOption("limit", "l", false); public static final SVNLookOption NO_DIFF_ADDED = new SVNLookOption("no-diff-added", null, true); public static final SVNLookOption NO_DIFF_DELETED = new SVNLookOption("no-diff-deleted", null, true); public static final SVNLookOption NON_RECURSIVE = new SVNLookOption("non-recursive", "N", true); public static final SVNLookOption REVISION = new SVNLookOption("revision", "r", false); public static final SVNLookOption REVPROP = new SVNLookOption("revprop", null, true); public static final SVNLookOption SHOW_IDS = new SVNLookOption("show-ids", null, true); public static final SVNLookOption TRANSACTION = new SVNLookOption("transaction", "t", false); public static final SVNLookOption VERBOSE = new SVNLookOption("verbose", "v", true); public static final SVNLookOption XML = new SVNLookOption("xml", null, true); public static final SVNLookOption EXTENSIONS = new SVNLookOption("extensions", "x", false); private SVNLookOption(String name, String alias, boolean unary) { super(name, alias, unary); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnlook.options"; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookPropGetCommand.java000066400000000000000000000123511177510526000333110ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookPropGetCommand extends SVNLookCommand { protected SVNLookPropGetCommand() { super("propget", new String[] { "pget", "pg" }); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); options.add(SVNLookOption.REVPROP); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); if (environment.getFirstArgument() == null) { SVNErrorMessage err = null; if (environment.isRevProp()) { err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Missing propname argument"); } else { err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Missing propname and repository path arguments"); } SVNErrorManager.error(err, SVNLogType.CLIENT); } else if (!environment.isRevProp() && environment.getSecondArgument() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Missing propname or repository path argument"); SVNErrorManager.error(err, SVNLogType.CLIENT); } String propName = environment.getFirstArgument(); SVNPropertyValue propValue = null; SVNLookClient client = environment.getClientManager().getLookClient(); if (environment.isRevision()) { if (environment.isRevProp()) { propValue = client.doGetRevisionProperty(environment.getRepositoryFile(), propName, getRevisionObject()); } else { propValue = client.doGetProperty(environment.getRepositoryFile(), propName, environment.getSecondArgument(), getRevisionObject()); } } else { if (environment.isRevProp()) { propValue = client.doGetRevisionProperty(environment.getRepositoryFile(), propName, environment.getTransaction()); } else { propValue = client.doGetProperty(environment.getRepositoryFile(), propName, environment.getSecondArgument(), environment.getTransaction()); } } if (propValue == null) { SVNErrorMessage err = null; if (environment.isRevProp()) { if (environment.isRevision()) { err = SVNErrorMessage.create(SVNErrorCode.PROPERTY_NOT_FOUND, "Property ''{0}'' not found on revision {1}", new Object[] { propName, String.valueOf(environment.getRevision()) } ); } else { err = SVNErrorMessage.create(SVNErrorCode.PROPERTY_NOT_FOUND, "Property ''{0}'' not found in transaction {1}", new Object[] { propName, String.valueOf(environment.getTransaction()) } ); } } else { if (environment.isRevision()) { err = SVNErrorMessage.create(SVNErrorCode.PROPERTY_NOT_FOUND, "Property ''{0}'' not found on path ''{1}'' in revision {2}", new Object[] { propName, environment.getSecondArgument(), SVNRevision.create(environment.getRevision()) } ); } else { err = SVNErrorMessage.create(SVNErrorCode.PROPERTY_NOT_FOUND, "Property ''{0}'' not found on path ''{1}'' in transaction {2}", new Object[] { propName, environment.getSecondArgument(), environment.getTransaction() } ); } } SVNErrorManager.error(err, SVNLogType.CLIENT); } if (propValue.isString()) { environment.getOut().print(propValue.getString()); } else { environment.getOut().print(propValue.getBytes()); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookPropListCommand.java000066400000000000000000000076551177510526000335200ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookPropListCommand extends SVNLookCommand { protected SVNLookPropListCommand() { super("proplist", new String[] { "plist", "pl" }); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); options.add(SVNLookOption.VERBOSE); options.add(SVNLookOption.REVPROP); options.add(SVNLookOption.XML); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); if (!environment.isRevProp() && environment.getFirstArgument() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Missing repository path argument"); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNLookClient client = environment.getClientManager().getLookClient(); SVNProperties props = null; if (environment.isRevision()) { if (environment.isRevProp()) { props = client.doGetRevisionProperties(environment.getRepositoryFile(), getRevisionObject()); } else { props = client.doGetProperties(environment.getRepositoryFile(), environment.getFirstArgument(), getRevisionObject()); } } else { if (environment.isRevProp()) { props = client.doGetRevisionProperties(environment.getRepositoryFile(), environment.getTransaction()); } else { props = client.doGetProperties(environment.getRepositoryFile(), environment.getFirstArgument(), environment.getTransaction()); } } if (props != null) { for (Iterator propNamesIter = props.nameSet().iterator(); propNamesIter.hasNext();) { String propName = (String) propNamesIter.next(); SVNPropertyData propData = new SVNPropertyData(propName, props.getSVNPropertyValue(propName), client.getOptions()); SVNPropertyValue propValue = propData.getValue(); if (environment.isVerbose()) { environment.getOut().print(" " + propName + " : "); if (propValue.isString()) { environment.getOut().println(propValue.getString()); } else { environment.getOut().println(SVNPropertyValue.getPropertyAsString(propValue)); } } else { environment.getOut().println(" " + propName); } } } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookTreeCommand.java000066400000000000000000000071421177510526000326320ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.text.MessageFormat; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.wc.admin.ISVNTreeHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminPath; import org.tmatesoft.svn.core.wc.admin.SVNLookClient; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookTreeCommand extends SVNLookCommand implements ISVNTreeHandler { protected SVNLookTreeCommand() { super("tree", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); options.add(SVNLookOption.REVISION); options.add(SVNLookOption.TRANSACTION); options.add(SVNLookOption.NON_RECURSIVE); options.add(SVNLookOption.SHOW_IDS); options.add(SVNLookOption.FULL_PATHS); return options; } public void run() throws SVNException { SVNLookCommandEnvironment environment = getSVNLookEnvironment(); SVNLookClient client = environment.getClientManager().getLookClient(); String path = environment.getFirstArgument(); if (environment.isRevision()) { client.doGetTree(environment.getRepositoryFile(), path, getRevisionObject(), environment.isShowIDs(), !environment.isNonRecursive(), this); } else { client.doGetTree(environment.getRepositoryFile(), path, environment.getTransaction(), environment.isShowIDs(), !environment.isNonRecursive(), this); } } public void handlePath(SVNAdminPath adminPath) throws SVNException { if (adminPath != null) { String indentation = null; if (!getSVNLookEnvironment().isFullPaths()) { indentation = ""; for (int i = 0; i < adminPath.getTreeDepth(); i++) { indentation += " "; } } String path = adminPath.getPath(); if (getSVNLookEnvironment().isFullPaths()) { path = path.startsWith("/") && !"/".equals(path) ? path.substring(1) : path; if (adminPath.isDir() && !"/".equals(path) && !path.endsWith("/")) { path += "/"; } getSVNLookEnvironment().getOut().print(path); } else { path = !"/".equals(path) ? SVNPathUtil.tail(path) : path; if (adminPath.isDir() && !"/".equals(path) && !path.endsWith("/")) { path += "/"; } getSVNLookEnvironment().getOut().print(indentation + path); } if (getSVNLookEnvironment().isShowIDs()) { String message = MessageFormat.format(" <{0}>", new Object[] { adminPath.getNodeID() != null ? adminPath.getNodeID() : "unknown" }); getSVNLookEnvironment().getOut().print(message); } getSVNLookEnvironment().getOut().println(); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookUUIDCommand.java000066400000000000000000000023251177510526000324770ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.io.SVNRepository; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookUUIDCommand extends SVNLookCommand { protected SVNLookUUIDCommand() { super("uuid", null); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { SVNRepository repository = getSVNLookEnvironment().getRepository(); String uuid = repository.getRepositoryUUID(true); getEnvironment().getOut().println(uuid); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnlook/SVNLookYoungestCommand.java000066400000000000000000000022731177510526000335500ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnlook; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNLookYoungestCommand extends SVNLookCommand { protected SVNLookYoungestCommand() { super("youngest", null); } protected Collection createSupportedOptions() { List options = new LinkedList(); return options; } public void run() throws SVNException { long revision = getSVNLookEnvironment().getRepository().getLatestRevision(); getEnvironment().getOut().println(revision); } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/000077500000000000000000000000001177510526000263615ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/SVNSync.java000066400000000000000000000052571177510526000305400ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNLauncher; import org.tmatesoft.svn.cli.SVNCommandLine; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNSync extends AbstractSVNLauncher { public static void main(String[] args) { new SVNSync().run(args); } protected AbstractSVNCommandEnvironment createCommandEnvironment() { return new SVNSyncCommandEnvironment(getProgramName(), System.out, System.err, System.in); } protected String getProgramName() { return "jsvnsync"; } protected boolean needArgs() { return true; } protected boolean needCommand() { return true; } protected void registerCommands() { AbstractSVNCommand.registerCommand(new SVNSyncInitializeCommand()); AbstractSVNCommand.registerCommand(new SVNSyncCopyRevPropsCommand()); AbstractSVNCommand.registerCommand(new SVNSyncSynchronizeCommand()); AbstractSVNCommand.registerCommand(new SVNSyncHelpCommand()); AbstractSVNCommand.registerCommand(new SVNSyncInfoCommand()); } protected void registerOptions() { SVNCommandLine.registerOption(SVNSyncOption.HELP); SVNCommandLine.registerOption(SVNSyncOption.QUESTION); SVNCommandLine.registerOption(SVNSyncOption.VERSION); SVNCommandLine.registerOption(SVNSyncOption.CONFIG_DIR); SVNCommandLine.registerOption(SVNSyncOption.SYNC_USERNAME); SVNCommandLine.registerOption(SVNSyncOption.SYNC_PASSWORD); SVNCommandLine.registerOption(SVNSyncOption.SOURCE_USERNAME); SVNCommandLine.registerOption(SVNSyncOption.SOURCE_PASSWORD); SVNCommandLine.registerOption(SVNSyncOption.USERNAME); SVNCommandLine.registerOption(SVNSyncOption.PASSWORD); SVNCommandLine.registerOption(SVNSyncOption.NO_AUTH_CACHE); SVNCommandLine.registerOption(SVNSyncOption.NON_INTERACTIVE); SVNCommandLine.registerOption(SVNSyncOption.QUIET); SVNCommandLine.registerOption(SVNSyncOption.TRUST_SERVER_CERT); } }svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/SVNSyncCommand.java000066400000000000000000000026011177510526000320250ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import java.util.Collection; import java.util.Collections; import org.tmatesoft.svn.cli.AbstractSVNCommand; /** * @version 1.3 * @author TMate Software Ltd. */ public abstract class SVNSyncCommand extends AbstractSVNCommand { private int myOutputPriority; public SVNSyncCommand(String name, String[] aliases, int outputPriority) { super(name, aliases); myOutputPriority = outputPriority; } public Collection getGlobalOptions() { return Collections.EMPTY_LIST; } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnsync.commands"; } protected SVNSyncCommandEnvironment getSVNSyncEnvironment() { return (SVNSyncCommandEnvironment) getEnvironment(); } public int getOutputPriority() { return myOutputPriority; } } SVNSyncCommandEnvironment.java000066400000000000000000000236021177510526000341770ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNOption; import org.tmatesoft.svn.cli.SVNCommandLine; import org.tmatesoft.svn.cli.SVNConsoleAuthenticationProvider; import org.tmatesoft.svn.cli.SVNOptionValue; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.ISVNAuthStoreHandler; import org.tmatesoft.svn.core.internal.wc.ISVNAuthenticationStorageOptions; import org.tmatesoft.svn.core.internal.wc.ISVNGnomeKeyringPasswordProvider; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNSyncCommandEnvironment extends AbstractSVNCommandEnvironment { private boolean myIsNonInteractive; private boolean myIsNoAuthCache; private String myUserName; private String myPassword; private String mySourceUsername; private String mySourcePassword; private String mySyncUsername; private String mySyncPassword; private String myConfigDir; private boolean myIsVersion; private boolean myIsQuiet; private boolean myIsHelp; private boolean myIsTrustServerCertificate; public boolean isNonInteractive() { return myIsNonInteractive; } public boolean isNoAuthCache() { return myIsNoAuthCache; } public String getUsername() { return myUserName; } public String getPassword() { return myPassword; } public String getSourceUsername() { return mySourceUsername; } public String getSourcePassword() { return mySourcePassword; } public String getSyncUsername() { return mySyncUsername; } public String getSyncPassword() { return mySyncPassword; } public String getConfigDir() { return myConfigDir; } public boolean isVersion() { return myIsVersion; } public boolean isQuiet() { return myIsQuiet; } public boolean isHelp() { return myIsHelp; } public SVNSyncCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { super(programName, out, err, in); } protected ISVNAuthenticationManager createClientAuthenticationManager() { File configDir = myConfigDir != null ? new File(myConfigDir) : SVNWCUtil.getDefaultConfigurationDirectory(); final DefaultSVNAuthenticationManager authManager = (DefaultSVNAuthenticationManager) SVNWCUtil.createDefaultAuthenticationManager(configDir, myUserName, myPassword, !myIsNoAuthCache); final ISVNAuthStoreHandler authStoreHandler; final ISVNGnomeKeyringPasswordProvider gnomeKeyringPasswordProvider; if (!myIsNonInteractive) { SVNConsoleAuthenticationProvider consoleAuthProvider = new SVNConsoleAuthenticationProvider(myIsTrustServerCertificate); authManager.setAuthenticationProvider(consoleAuthProvider); authStoreHandler = consoleAuthProvider; gnomeKeyringPasswordProvider = consoleAuthProvider; } else { authStoreHandler = null; gnomeKeyringPasswordProvider = null; } ISVNAuthenticationStorageOptions authOpts = new ISVNAuthenticationStorageOptions() { public boolean isNonInteractive() throws SVNException { return myIsNonInteractive; } public ISVNAuthStoreHandler getAuthStoreHandler() throws SVNException { return authStoreHandler; } public boolean isSSLPassphrasePromptSupported() { return authManager.isSSLPassphrasePromtSupported(); } public ISVNGnomeKeyringPasswordProvider getGnomeKeyringPasswordProvider() { return gnomeKeyringPasswordProvider; } }; authManager.setAuthenticationStorageOptions(authOpts); return authManager; } protected DefaultSVNOptions createClientOptions() { return null; } protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNSyncOption.NON_INTERACTIVE) { myIsNonInteractive = true; } else if (option == SVNSyncOption.NO_AUTH_CACHE) { myIsNoAuthCache = true; } else if (option == SVNSyncOption.USERNAME) { myUserName = optionValue.getValue(); } else if (option == SVNSyncOption.PASSWORD) { myPassword = optionValue.getValue(); } else if (option == SVNSyncOption.SOURCE_USERNAME) { mySourceUsername = optionValue.getValue(); } else if (option == SVNSyncOption.SOURCE_PASSWORD) { mySourcePassword = optionValue.getValue(); } else if (option == SVNSyncOption.SYNC_USERNAME) { mySyncUsername = optionValue.getValue(); } else if (option == SVNSyncOption.SYNC_PASSWORD) { mySyncPassword = optionValue.getValue(); } else if (option == SVNSyncOption.CONFIG_DIR) { myConfigDir = optionValue.getValue(); } else if (option == SVNSyncOption.VERSION) { myIsVersion = true; } else if (option == SVNSyncOption.QUIET) { myIsQuiet = true; } else if (option == SVNSyncOption.TRUST_SERVER_CERT) { myIsTrustServerCertificate = true; } else if (option == SVNSyncOption.HELP || option == SVNSyncOption.QUESTION) { myIsHelp = true; } } protected void validateOptions(SVNCommandLine commandLine) throws SVNException { super.validateOptions(commandLine); if ((myUserName != null || myPassword != null) && (mySourceUsername != null || mySourcePassword != null) && (mySyncUsername != null || mySyncPassword != null)) { SVNErrorMessage error = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Cannot use --username or --password with any of --source-username, --source-password, --sync-username, or --sync-password."); SVNErrorManager.error(error, SVNLogType.CLIENT); } if (myUserName != null) { mySourceUsername = myUserName; mySyncUsername = myUserName; } if (myPassword != null) { mySourcePassword = myPassword; mySyncPassword = myPassword; } if (myIsTrustServerCertificate && !myIsNonInteractive) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "--trust-server-cert requires --non-interactive"); SVNErrorManager.error(err, SVNLogType.CLIENT); } } protected String refineCommandName(String commandName, SVNCommandLine commandLine) throws SVNException { for (Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); AbstractSVNOption option = optionValue.getOption(); if (option == SVNSyncOption.HELP || option == SVNSyncOption.QUESTION) { myIsHelp = true; } else if (option == SVNSyncOption.VERSION) { myIsVersion = true; } } if (myIsHelp) { List newArguments = commandName != null ? Collections.singletonList(commandName) : Collections.EMPTY_LIST; setArguments(newArguments); return "help"; } if (commandName == null) { if (isVersion()) { SVNSyncCommand versionCommand = new SVNSyncCommand("--version", null, 0) { protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNSyncOption.VERSION); return options; } public void run() throws SVNException { AbstractSVNCommand helpCommand = AbstractSVNCommand.getCommand("help"); helpCommand.init(SVNSyncCommandEnvironment.this); helpCommand.run(); } }; AbstractSVNCommand.registerCommand(versionCommand); return "--version"; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Subcommand argument required"); SVNErrorManager.error(err, SVNLogType.CLIENT); } return commandName; } protected String getCommandLineClientName() { return "svnsync"; } } SVNSyncCopyRevPropsCommand.java000066400000000000000000000137751177510526000343200ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNSyncCopyRevPropsCommand extends SVNSyncCommand implements ISVNAdminEventHandler { public SVNSyncCopyRevPropsCommand() { super("copy-revprops", null, 1); } protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNSyncOption.NON_INTERACTIVE); options.add(SVNSyncOption.NO_AUTH_CACHE); options.add(SVNSyncOption.USERNAME); options.add(SVNSyncOption.PASSWORD); options.add(SVNSyncOption.TRUST_SERVER_CERT); options.add(SVNSyncOption.SOURCE_USERNAME); options.add(SVNSyncOption.SOURCE_PASSWORD); options.add(SVNSyncOption.SYNC_USERNAME); options.add(SVNSyncOption.SYNC_PASSWORD); options.add(SVNSyncOption.CONFIG_DIR); options.add(SVNSyncOption.QUIET); return options; } public void run() throws SVNException { List arguments = getSVNSyncEnvironment().getArguments(); if (arguments.size() > 2) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (arguments.isEmpty()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNRevision startRevision = null; SVNRevision endRevision = null; long startRevisionNumber = 0; long endRevisionNumber = -1; if (arguments.size() == 2) { String revString = (String) arguments.remove(arguments.size() - 1); SVNRevision[] revisions = getEnvironment().parseRevision(revString); if (revisions == null || revisions[0].isLocal() || revisions[1].isLocal()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "''{0}'' is not a valid revision range", revString); SVNErrorManager.error(err, SVNLogType.CLIENT); } startRevision = revisions[0]; endRevision = revisions[1]; if (startRevision == SVNRevision.HEAD) { startRevisionNumber = -1; } else { startRevisionNumber = startRevision.getNumber(); if (!SVNRevision.isValidRevisionNumber(startRevisionNumber)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Invalid revision number ({0})", String.valueOf(startRevisionNumber)); SVNErrorManager.error(err, SVNLogType.CLIENT); } } if (!endRevision.isValid()) { endRevisionNumber = startRevisionNumber; } else if (endRevision != SVNRevision.HEAD) { endRevisionNumber = endRevision.getNumber(); if (!SVNRevision.isValidRevisionNumber(endRevisionNumber)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Invalid revision number ({0})", String.valueOf(endRevisionNumber)); SVNErrorManager.error(err, SVNLogType.CLIENT); } } } List targets = getEnvironment().combineTargets(null, false); if (targets.size() != 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPath toURL = new SVNPath((String) targets.get(0)); if (!toURL.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Path ''{0}'' is not a URL", toURL.getTarget()); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.doCopyRevisionProperties(toURL.getURL(), startRevisionNumber, endRevisionNumber); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.REVISION_PROPERTIES_COPIED || event.getAction() == SVNAdminEventAction.NORMALIZED_PROPERTIES) { if (!getSVNSyncEnvironment().isQuiet()) { getSVNSyncEnvironment().getOut().println(event.getMessage()); } } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/SVNSyncHelpCommand.java000066400000000000000000000110231177510526000326340ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import java.text.MessageFormat; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNSyncHelpCommand extends SVNSyncCommand { private static final String GENERIC_HELP_HEADER = "general usage: {0} SUBCOMMAND DEST_URL [ARGS & OPTIONS ...]\n" + "Type ''{0} help '' for help on a specific subcommand.\n" + "Type ''{0} --version'' to see the program version and RA modules.\n" + "\n" + "Available subcommands:"; private static final String VERSION_HELP_FOOTER = "\nThe following repository access (RA) modules are available:\n\n" + "* org.tmatesoft.svn.core.internal.io.dav : Module for accessing a repository via WebDAV protocol.\n" + " - handles 'http' scheme\n" + " - handles 'https' scheme\n" + "* org.tmatesoft.svn.core.internal.io.svn: Module for accessing a repository using the svn network protocol.\n" + " - handles 'svn' scheme\n" + "* org.tmatesoft.svn.core.internal.io.fs: Module for accessing a repository on local disk.\n" + " - handles 'file' scheme (only FSFS repositories are supported)\n"; public SVNSyncHelpCommand() { super("help", new String[] {"?", "h"}, 2); } protected Collection createSupportedOptions() { return new LinkedList(); } public void run() throws SVNException { if (!getSVNSyncEnvironment().getArguments().isEmpty()) { for (Iterator commands = getSVNSyncEnvironment().getArguments().iterator(); commands.hasNext();) { String commandName = (String) commands.next(); AbstractSVNCommand command = AbstractSVNCommand.getCommand(commandName); if (command == null) { getSVNSyncEnvironment().getErr().println("\"" + commandName + "\": unknown command.\n"); continue; } String help = SVNCommandUtil.getCommandHelp(command, getEnvironment().getProgramName(), true); getSVNSyncEnvironment().getOut().println(help); } } else if (getSVNSyncEnvironment().isVersion()) { String version = SVNCommandUtil.getVersion(getEnvironment(), getSVNSyncEnvironment().isQuiet()); getEnvironment().getOut().println(version); getEnvironment().getOut().println(VERSION_HELP_FOOTER); } else if (getSVNSyncEnvironment().getArguments().isEmpty()) { Comparator commandComparator = new Comparator() { public int compare(Object o1, Object o2) { AbstractSVNCommand c1 = (AbstractSVNCommand) o1; AbstractSVNCommand c2 = (AbstractSVNCommand) o2; if (c1 instanceof SVNSyncCommand && c2 instanceof SVNSyncCommand) { SVNSyncCommand syncCommand1 = (SVNSyncCommand) c1; SVNSyncCommand syncCommand2 = (SVNSyncCommand) c2; if (syncCommand1.getOutputPriority() != syncCommand2.getOutputPriority()) { return syncCommand1.getOutputPriority() < syncCommand2.getOutputPriority() ? -1 : 1; } } return c1.getName().compareTo(c2.getName()); } }; String help = SVNCommandUtil.getGenericHelp(getEnvironment().getProgramName(), GENERIC_HELP_HEADER, null, commandComparator); getSVNSyncEnvironment().getOut().print(help); } else { String message = MessageFormat.format("Type ''{0} help'' for usage.", new Object[] { getSVNSyncEnvironment().getProgramName() }); getSVNSyncEnvironment().getOut().println(message); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/SVNSyncInfoCommand.java000066400000000000000000000064531177510526000326520ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNSyncInfo; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNSyncInfoCommand extends SVNSyncCommand { public SVNSyncInfoCommand() { super("info", null, 1); } protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNSyncOption.NON_INTERACTIVE); options.add(SVNSyncOption.NO_AUTH_CACHE); options.add(SVNSyncOption.USERNAME); options.add(SVNSyncOption.PASSWORD); options.add(SVNSyncOption.TRUST_SERVER_CERT); options.add(SVNSyncOption.SOURCE_USERNAME); options.add(SVNSyncOption.SOURCE_PASSWORD); options.add(SVNSyncOption.SYNC_USERNAME); options.add(SVNSyncOption.SYNC_PASSWORD); options.add(SVNSyncOption.CONFIG_DIR); return options; } public void run() throws SVNException { List targets = getEnvironment().combineTargets(null, false); if (targets.size() < 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (targets.size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPath toURL = new SVNPath((String) targets.get(0)); if (!toURL.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Path ''{0}'' is not a URL", toURL.getTarget()); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); SVNSyncInfo info = client.doInfo(toURL.getURL()); getSVNSyncEnvironment().getOut().println("Source URL: " + info.getSrcURL()); if (info.getSourceRepositoryUUID() != null) { getSVNSyncEnvironment().getOut().println("Source Repository UUID: " + info.getSourceRepositoryUUID()); } if (SVNRevision.isValidRevisionNumber(info.getLastMergedRevision())) { getSVNSyncEnvironment().getOut().println("Last Merged Revision: " + info.getLastMergedRevision()); } } } SVNSyncInitializeCommand.java000066400000000000000000000100761177510526000337750ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNSyncInitializeCommand extends SVNSyncCommand implements ISVNAdminEventHandler { public SVNSyncInitializeCommand() { super("initialize", new String[] { "init" }, 0); } protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNSyncOption.NON_INTERACTIVE); options.add(SVNSyncOption.NO_AUTH_CACHE); options.add(SVNSyncOption.USERNAME); options.add(SVNSyncOption.PASSWORD); options.add(SVNSyncOption.TRUST_SERVER_CERT); options.add(SVNSyncOption.SOURCE_USERNAME); options.add(SVNSyncOption.SOURCE_PASSWORD); options.add(SVNSyncOption.SYNC_USERNAME); options.add(SVNSyncOption.SYNC_PASSWORD); options.add(SVNSyncOption.CONFIG_DIR); options.add(SVNSyncOption.QUIET); return options; } public void run() throws SVNException { List targets = getEnvironment().combineTargets(null, false); if (targets.size() < 2) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (targets.size() > 2) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPath toURL = new SVNPath((String) targets.get(0)); if (!toURL.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Path ''{0}'' is not a URL", toURL.getTarget()); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPath fromURL = new SVNPath((String) targets.get(1)); if (!fromURL.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Path ''{0}'' is not a URL", fromURL.getTarget()); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.doInitialize(fromURL.getURL(), toURL.getURL()); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.REVISION_PROPERTIES_COPIED || event.getAction() == SVNAdminEventAction.NORMALIZED_PROPERTIES) { if (!getSVNSyncEnvironment().isQuiet()) { getSVNSyncEnvironment().getOut().println(event.getMessage()); } } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/SVNSyncOption.java000066400000000000000000000044231177510526000317230ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import org.tmatesoft.svn.cli.AbstractSVNOption; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNSyncOption extends AbstractSVNOption { public static final SVNSyncOption HELP = new SVNSyncOption("help", "h", true); public static final SVNSyncOption QUESTION = new SVNSyncOption("?", null, true); public static final SVNSyncOption VERSION = new SVNSyncOption("version", null, true); public static final SVNSyncOption CONFIG_DIR = new SVNSyncOption("config-dir", null, false); public static final SVNSyncOption SYNC_PASSWORD = new SVNSyncOption("sync-password", null, false); public static final SVNSyncOption SYNC_USERNAME = new SVNSyncOption("sync-username", null, false); public static final SVNSyncOption SOURCE_PASSWORD = new SVNSyncOption("source-password", null, false); public static final SVNSyncOption SOURCE_USERNAME = new SVNSyncOption("source-username", null, false); public static final SVNSyncOption USERNAME = new SVNSyncOption("username", null, false); public static final SVNSyncOption PASSWORD = new SVNSyncOption("password", null, false); public static final SVNSyncOption NO_AUTH_CACHE = new SVNSyncOption("no-auth-cache", null, true); public static final SVNSyncOption NON_INTERACTIVE = new SVNSyncOption("non-interactive", null, true); public static final SVNSyncOption QUIET = new SVNSyncOption("quiet", "q", true); public static final SVNSyncOption TRUST_SERVER_CERT = new SVNSyncOption("trust-server-cert", null, true); private SVNSyncOption(String name, String alias, boolean unary) { super(name, alias, unary); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnsync.options"; } } SVNSyncSynchronizeCommand.java000066400000000000000000000101031177510526000341760ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnsync/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnsync; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNSyncSynchronizeCommand extends SVNSyncCommand implements ISVNAdminEventHandler { public SVNSyncSynchronizeCommand() { super("synchronize", new String[]{"sync"}, 0); } protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNSyncOption.NON_INTERACTIVE); options.add(SVNSyncOption.NO_AUTH_CACHE); options.add(SVNSyncOption.USERNAME); options.add(SVNSyncOption.PASSWORD); options.add(SVNSyncOption.TRUST_SERVER_CERT); options.add(SVNSyncOption.SOURCE_USERNAME); options.add(SVNSyncOption.SOURCE_PASSWORD); options.add(SVNSyncOption.SYNC_USERNAME); options.add(SVNSyncOption.SYNC_PASSWORD); options.add(SVNSyncOption.CONFIG_DIR); options.add(SVNSyncOption.QUIET); return options; } public void run() throws SVNException { List targets = getEnvironment().combineTargets(null, false); if (targets.size() < 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS); SVNErrorManager.error(err, SVNLogType.CLIENT); } if (targets.size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNPath toURL = new SVNPath((String) targets.get(0)); if (!toURL.isURL()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "Path ''{0}'' is not a URL", toURL.getTarget()); SVNErrorManager.error(err, SVNLogType.CLIENT); } SVNAdminClient client = getEnvironment().getClientManager().getAdminClient(); client.setEventHandler(this); client.setReplayHandler(new ISVNLogEntryHandler() { public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { getEnvironment().getOut().println("Committed revision " + logEntry.getRevision() + "."); } }); client.doSynchronize(toURL.getURL()); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.REVISION_PROPERTIES_COPIED || event.getAction() == SVNAdminEventAction.NORMALIZED_PROPERTIES) { if (!getSVNSyncEnvironment().isQuiet()) { getSVNSyncEnvironment().getOut().println(event.getMessage()); } } } public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnversion/000077500000000000000000000000001177510526000270725ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnversion/SVNVersion.java000066400000000000000000000035121177510526000317520ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnversion; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNLauncher; import org.tmatesoft.svn.cli.SVNCommandLine; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNVersion extends AbstractSVNLauncher { public static void main(String[] args) { new SVNVersion().run(args); } protected AbstractSVNCommandEnvironment createCommandEnvironment() { return new SVNVersionCommandEnvironment(getProgramName(), System.out, System.err, System.in); } protected String getProgramName() { return "jsvnversion"; } protected void registerCommands() { AbstractSVNCommand.registerCommand(new SVNVersionCommand()); AbstractSVNCommand.registerCommand(new SVNVersionHelpCommand()); } protected void registerOptions() { SVNCommandLine.registerOption(SVNVersionOption.COMMITTED); SVNCommandLine.registerOption(SVNVersionOption.NO_NEWLINE); SVNCommandLine.registerOption(SVNVersionOption.HELP); SVNCommandLine.registerOption(SVNVersionOption.VERSION); } protected boolean needArgs() { return false; } protected boolean needCommand() { return false; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnversion/SVNVersionCommand.java000066400000000000000000000050621177510526000332530ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnversion; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNPath; import org.tmatesoft.svn.core.wc.SVNClientManager; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNVersionCommand extends AbstractSVNCommand { public SVNVersionCommand() { super("", null); } protected Collection createSupportedOptions() { List options = new ArrayList(); options.add(SVNVersionOption.NO_NEWLINE); options.add(SVNVersionOption.COMMITTED); options.add(SVNVersionOption.HELP); options.add(SVNVersionOption.VERSION); return options; } protected SVNVersionCommandEnvironment getSVNVersionEnvironment() { return (SVNVersionCommandEnvironment) getEnvironment(); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnversion.commands"; } public void run() throws SVNException { List targets = getEnvironment().combineTargets(null, false); if (targets.isEmpty()) { targets.add(""); } SVNPath target = new SVNPath((String) targets.get(0)); if (target.isURL()) { target = new SVNPath(""); targets.add(0, ""); } String trailURL = (String) (targets.size() > 1 ? targets.get(1) : null); if (target.isFile()) { String id = SVNClientManager.newInstance().getWCClient().doGetWorkingCopyID(target.getFile(), trailURL, getSVNVersionEnvironment().isCommitted()); if (id != null) { getEnvironment().getOut().print(id); if (!getSVNVersionEnvironment().isNoNewLine()) { getEnvironment().getOut().println(); } } } } public Collection getGlobalOptions() { return Collections.EMPTY_LIST; } } SVNVersionCommandEnvironment.java000066400000000000000000000105571177510526000354260ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnversion/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnversion; import java.io.InputStream; import java.io.PrintStream; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.AbstractSVNCommandEnvironment; import org.tmatesoft.svn.cli.AbstractSVNOption; import org.tmatesoft.svn.cli.SVNCommandLine; import org.tmatesoft.svn.cli.SVNOptionValue; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.wc.SVNWCUtil; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNVersionCommandEnvironment extends AbstractSVNCommandEnvironment { private boolean myIsHelp; private boolean myIsVersion; private boolean myIsCommitted; private boolean myIsNoNewLine; public SVNVersionCommandEnvironment(String programName, PrintStream out, PrintStream err, InputStream in) { super(programName, out, err, in); } public boolean isHelp() { return myIsHelp; } public boolean isVersion() { return myIsVersion; } public boolean isCommitted() { return myIsCommitted; } public boolean isNoNewLine() { return myIsNoNewLine; } protected ISVNAuthenticationManager createClientAuthenticationManager() { return SVNWCUtil.createDefaultAuthenticationManager(); } protected DefaultSVNOptions createClientOptions() { return SVNWCUtil.createDefaultOptions(true); } protected void initOption(SVNOptionValue optionValue) throws SVNException { AbstractSVNOption option = optionValue.getOption(); if (option == SVNVersionOption.COMMITTED) { myIsCommitted = true; } else if (option == SVNVersionOption.NO_NEWLINE) { myIsNoNewLine = true; } else if (option == SVNVersionOption.HELP) { myIsHelp = true; } else if (option == SVNVersionOption.VERSION) { myIsVersion = true; } } protected String refineCommandName(String commandName, SVNCommandLine commandLine) throws SVNException { for (Iterator options = commandLine.optionValues(); options.hasNext();) { SVNOptionValue optionValue = (SVNOptionValue) options.next(); AbstractSVNOption option = optionValue.getOption(); if (option == SVNVersionOption.HELP) { myIsHelp = true; } else if (option == SVNVersionOption.VERSION) { myIsVersion = true; } } if (myIsHelp) { List newArguments = commandName != null ? Collections.singletonList(commandName) : Collections.EMPTY_LIST; setArguments(newArguments); return "help"; } if (isVersion()) { SVNVersionCommand versionCommand = new SVNVersionCommand() { protected Collection createSupportedOptions() { LinkedList options = new LinkedList(); options.add(SVNVersionOption.VERSION); return options; } public void run() throws SVNException { AbstractSVNCommand helpCommand = AbstractSVNCommand.getCommand("help"); helpCommand.init(SVNVersionCommandEnvironment.this); helpCommand.run(); } public String getName() { return "--version"; } }; AbstractSVNCommand.registerCommand(versionCommand); return "--version"; } return ""; } protected String getCommandLineClientName() { return "svnversion"; } } SVNVersionHelpCommand.java000066400000000000000000000042371177510526000340100ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnversion/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnversion; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.tmatesoft.svn.cli.AbstractSVNCommand; import org.tmatesoft.svn.cli.SVNCommandUtil; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNVersionHelpCommand extends AbstractSVNCommand { public SVNVersionHelpCommand() { super("help", null); } protected Collection createSupportedOptions() { List options = new ArrayList(); options.add(SVNVersionOption.VERSION); options.add(SVNVersionOption.HELP); return options; } public Collection getGlobalOptions() { return Collections.EMPTY_LIST; } protected SVNVersionCommandEnvironment getSVNVersionEnvironment() { return (SVNVersionCommandEnvironment) getEnvironment(); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnversion.commands"; } public void run() throws SVNException { if (getSVNVersionEnvironment().isHelp()) { String help = SVNCommandUtil.getCommandHelp(AbstractSVNCommand.getCommand(""), getEnvironment().getProgramName(), true); getEnvironment().getOut().println(help); } else if (getSVNVersionEnvironment().isVersion()) { String help = SVNCommandUtil.getVersion(getEnvironment(), false); getEnvironment().getOut().println(help); } else { getEnvironment().getOut().println("Type '" + getEnvironment().getProgramName() + " --help' for usage."); } } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svnversion/SVNVersionOption.java000066400000000000000000000025151177510526000331450ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.cli.svnversion; import org.tmatesoft.svn.cli.AbstractSVNOption; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNVersionOption extends AbstractSVNOption { public static final SVNVersionOption NO_NEWLINE = new SVNVersionOption("no-newline", "n", true); public static final SVNVersionOption COMMITTED = new SVNVersionOption("committed", "c", true); public static final SVNVersionOption HELP = new SVNVersionOption("help", "h", true); public static final SVNVersionOption VERSION = new SVNVersionOption("version", null, true); private SVNVersionOption(String name, String alias, boolean unary) { super(name, alias, unary); } protected String getResourceBundleName() { return "org.tmatesoft.svn.cli.svnversion.options"; } } svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/000077500000000000000000000000001177510526000215755ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/000077500000000000000000000000001177510526000223645ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/000077500000000000000000000000001177510526000243725ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/000077500000000000000000000000001177510526000252005ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/000077500000000000000000000000001177510526000257475ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svn/000077500000000000000000000000001177510526000265555ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svn/commands.properties000066400000000000000000000761361177510526000325110ustar00rootroot00000000000000help.description=Describe\ the\ usage\ of\ this\ program\ or\ its\ subcommands.\n\ usage:\ help\ [SUBCOMMAND...] status.description=\ Print\ the\ status\ of\ working\ copy\ files\ and\ directories.\n\ usage:\ status\ [PATH...]\n\ \n\ \ \ With\ no\ args,\ print\ only\ locally\ modified\ items\ (no\ network\ access).\n\ \ \ With\ -q,\ print\ only\ summary\ information\ about\ locally\ modified\ items.\n\ \ \ With\ -u,\ add\ working\ revision\ and\ server\ out-of-date\ information.\n\ \ \ With\ -v,\ print\ full\ revision\ information\ on\ every\ item.\n\ \n\ \ \ The\ first\ seven\ columns\ in\ the\ output\ are\ each\ one\ character\ wide:\n\ \ \ \ \ First\ column:\ Says\ if\ item\ was\ added,\ deleted,\ or\ otherwise\ changed\n\ \ \ \ \ \ \ '\ '\ no\ modifications\n\ \ \ \ \ \ \ 'A'\ Added\n\ \ \ \ \ \ \ 'C'\ Conflicted\n\ \ \ \ \ \ \ 'D'\ Deleted\n\ \ \ \ \ \ \ 'I'\ Ignored\n\ \ \ \ \ \ \ 'M'\ Modified\n\ \ \ \ \ \ \ 'R'\ Replaced\n\ \ \ \ \ \ \ 'X'\ an\ unversioned\ directory\ created\ by\ an\ externals\ definition\n\ \ \ \ \ \ \ '?'\ item\ is\ not\ under\ version\ control\n\ \ \ \ \ \ \ '!'\ item\ is\ missing\ (removed\ by\ non-svn\ command)\ or\ incomplete\n\ \ \ \ \ \ \ '~'\ versioned\ item\ obstructed\ by\ some\ item\ of\ a\ different\ kind\n\ \ \ \ \ Second\ column:\ Modifications\ of\ a\ file's\ or\ directory's\ properties\n\ \ \ \ \ \ \ '\ '\ no\ modifications\n\ \ \ \ \ \ \ 'C'\ Conflicted\n\ \ \ \ \ \ \ 'M'\ Modified\n\ \ \ \ \ Third\ column:\ Whether\ the\ working\ copy\ directory\ is\ locked\n\ \ \ \ \ \ \ '\ '\ not\ locked\n\ \ \ \ \ \ \ 'L'\ locked\n\ \ \ \ \ Fourth\ column:\ Scheduled\ commit\ will\ contain\ addition-with-history\n\ \ \ \ \ \ \ '\ '\ no\ history\ scheduled\ with\ commit\n\ \ \ \ \ \ \ '+'\ history\ scheduled\ with\ commit\n\ \ \ \ \ Fifth\ column:\ Whether\ the\ item\ is\ switched\ or\ a\ file\ external\n\ \ \ \ \ \ \ '\ '\ normal\n\ \ \ \ \ \ \ 'S'\ the\ item\ has\ a\ Switched\ URL\ relative\ to\ the\ parent\n\ \ \ \ \ \ \ 'X'\ a\ versioned\ file\ created\ by\ an\ eXternals\ definition\n\ \ \ \ \ Sixth\ column:\ Repository\ lock\ token\n\ \ \ \ \ \ \ (without\ -u)\n\ \ \ \ \ \ \ '\ '\ no\ lock\ token\n\ \ \ \ \ \ \ 'K'\ lock\ token\ present\n\ \ \ \ \ \ \ (with\ -u)\n\ \ \ \ \ \ \ '\ '\ not\ locked\ in\ repository,\ no\ lock\ token\n\ \ \ \ \ \ \ 'K'\ locked\ in\ repository,\ lock\ toKen\ present\n\ \ \ \ \ \ \ 'O'\ locked\ in\ repository,\ lock\ token\ in\ some\ Other\ working\ copy\n\ \ \ \ \ \ \ 'T'\ locked\ in\ repository,\ lock\ token\ present\ but\ sTolen\n\ \ \ \ \ \ \ 'B'\ not\ locked\ in\ repository,\ lock\ token\ present\ but\ Broken\n\ \ \ \ \ Seventh\ column:\ Whether\ the\ item\ is\ the\ victim\ of\ a\ tree\ conflict\n\ \ \ \ \ \ \ '\ '\ normal\n\ \ \ \ \ \ \ 'C'\ tree-Conflicted\n\ \ \ \ \ If\ the\ item\ is\ a\ tree\ conflict\ victim,\ an\ additional\ line\ is\ printed\n\ \ \ \ \ after\ the\ item's\ status\ line,\ explaining\ the\ nature\ of\ the\ conflict.\n\ \n\ \ \ The\ out-of-date\ information\ appears\ in\ the\ ninth\ column\ (with\ -u):\n\ \ \ \ \ \ \ '*'\ a\ newer\ revision\ exists\ on\ the\ server\n\ \ \ \ \ \ \ '\ '\ the\ working\ copy\ is\ up\ to\ date\n\ \n\ \ \ Remaining\ fields\ are\ variable\ width\ and\ delimited\ by\ spaces:\n\ \ \ \ \ The\ working\ revision\ (with\ -u\ or\ -v)\n\ \ \ \ \ The\ last\ committed\ revision\ and\ last\ committed\ author\ (with\ -v)\n\ \ \ \ \ The\ working\ copy\ path\ is\ always\ the\ final\ field,\ so\ it\ can\n\ \ \ \ \ \ \ include\ spaces.\n\ \n\ \ \ Example\ output:\n\ \ \ \ \ svn\ status\ wc\n\ \ \ \ \ \ M\ \ \ \ \ wc/bar.c\n\ \ \ \ \ A\ \ +\ \ \ wc/qax.c\n\ \n\ \ \ \ \ svn\ status\ -u\ wc\n\ \ \ \ \ \ M\ \ \ \ \ \ \ \ \ \ \ 965\ \ \ \ wc/bar.c\n\ \ \ \ \ \ \ \ \ \ \ \ *\ \ \ \ \ 965\ \ \ \ wc/foo.c\n\ \ \ \ \ A\ \ +\ \ \ \ \ \ \ \ \ 965\ \ \ \ wc/qax.c\n\ \ \ \ \ Status\ against\ revision:\ \ \ 981\n\ \n\ \ \ \ \ svn\ status\ --show-updates\ --verbose\ wc\n\ \ \ \ \ \ M\ \ \ \ \ \ \ \ \ \ \ 965\ \ \ \ \ \ \ 938\ shurik\ \ \ \ \ \ \ wc/bar.c\n\ \ \ \ \ \ \ \ \ \ \ \ *\ \ \ \ \ 965\ \ \ \ \ \ \ 922\ semen\ \ \ \ \ \ \ \ wc/foo.c\n\ \ \ \ \ A\ \ +\ \ \ \ \ \ \ \ \ 965\ \ \ \ \ \ \ 687\ alex\ \ \ \ \ \ \ \ \ wc/qax.c\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 965\ \ \ \ \ \ \ 687\ alex\ \ \ \ \ \ \ \ \ wc/zig.c\n\ \ \ \ \ Status\ against\ revision:\ \ \ 981\n\ \n\ \ \ \ \ svn\ status\n\ \ \ \ \ \ M\ \ \ \ \ \ wc/bar.c\n\ \ \ \ \ !\ \ \ \ \ C\ wc/qaz.c\n\ \ \ \ \ \ \ \ \ \ \ >\ \ \ local\ missing,\ incoming\ edit\ upon\ update\n\ \ \ \ \ D\ \ \ \ \ \ \ wc/qax.c propget.description=\ Print\ the\ value\ of\ a\ property\ on\ files,\ dirs,\ or\ revisions.\n\ usage:\ 1.\ propget\ PROPNAME\ [TARGET[@REV]...]\n\ \ \ \ \ \ \ \ 2.\ propget\ PROPNAME\ --revprop\ -r\ REV\ [TARGET]\n\ \n\ \ \ 1.\ Prints\ versioned\ props.\ If\ specified,\ REV\ determines\ in\ which\n\ \ \ \ \ \ revision\ the\ target\ is\ first\ looked\ up.\n\ \ \ 2.\ Prints\ unversioned\ remote\ prop\ on\ repos\ revision.\n\ \ \ \ \ \ TARGET\ only\ determines\ which\ repository\ to\ access.\n\ \n\ \ \ By\ default,\ this\ subcommand\ will\ add\ an\ extra\ newline\ to\ the\ end\n\ \ \ of\ the\ property\ values\ so\ that\ the\ output\ looks\ pretty.\ \ Also,\n\ \ \ whenever\ there\ are\ multiple\ paths\ involved,\ each\ property\ value\n\ \ \ is\ prefixed\ with\ the\ path\ with\ which\ it\ is\ associated.\ \ Use\ the\n\ \ \ --strict\ option\ to\ disable\ these\ beautifications\ (useful\ when\n\ \ \ redirecting\ a\ binary\ property\ value\ to\ a\ file,\ but\ available\ only\n\ \ \ if\ you\ supply\ a\ single\ TARGET\ to\ a\ non-recursive\ propget\ operation). proplist.description=\ List\ all\ properties\ on\ files,\ dirs,\ or\ revisions.\n\ usage:\ 1.\ proplist\ [TARGET[@REV]...]\n\ \ \ \ \ \ \ \ 2.\ proplist\ --revprop\ -r\ REV\ [TARGET]\n\ \n\ \ \ 1.\ Lists\ versioned\ props.\ If\ specified,\ REV\ determines\ in\ which\n\ \ \ \ \ \ revision\ the\ target\ is\ first\ looked\ up.\n\ \ \ 2.\ Lists\ unversioned\ remote\ props\ on\ repos\ revision.\n\ \ \ \ \ \ TARGET\ only\ determines\ which\ repository\ to\ access. propset.description=\ Set\ the\ value\ of\ a\ property\ on\ files,\ dirs,\ or\ revisions.\n\ usage:\ 1.\ propset\ PROPNAME\ PROPVAL\ PATH...\n\ \ \ \ \ \ \ \ 2.\ propset\ PROPNAME\ --revprop\ -r\ REV\ PROPVAL\ [TARGET]\n\ \n\ \ \ 1.\ Changes\ a\ versioned\ file\ or\ directory\ property\ in\ a\ working\ copy.\n\ \ \ 2.\ Changes\ an\ unversioned\ property\ on\ a\ repository\ revision.\n\ \ \ \ \ \ (TARGET\ only\ determines\ which\ repository\ to\ access.)\n\ \n\ \ \ The\ value\ may\ be\ provided\ with\ the\ --file\ option\ instead\ of\ PROPVAL.\n\ \n\ \ \ Note:\ svn\ recognizes\ the\ following\ special\ versioned\ properties\n\ \ \ but\ will\ store\ any\ arbitrary\ properties\ set:\n\ \ \ \ \ svn:ignore\ \ \ \ \ -\ A\ newline\ separated\ list\ of\ file\ glob\ patterns\ to\ ignore.\n\ \ \ \ \ svn:keywords\ \ \ -\ Keywords\ to\ be\ expanded.\ \ Valid\ keywords\ are:\n\ \ \ \ \ \ \ URL,\ HeadURL\ \ \ \ \ \ \ \ \ \ \ \ \ -\ The\ URL\ for\ the\ head\ version\ of\ the\ object.\n\ \ \ \ \ \ \ Author,\ LastChangedBy\ \ \ \ -\ The\ last\ person\ to\ modify\ the\ file.\n\ \ \ \ \ \ \ Date,\ LastChangedDate\ \ \ \ -\ The\ date/time\ the\ object\ was\ last\ modified.\n\ \ \ \ \ \ \ Rev,\ Revision,\ \ \ \ \ \ \ \ \ \ \ -\ The\ last\ revision\ the\ object\ changed.\n\ \ \ \ \ \ \ LastChangedRevision\n\ \ \ \ \ \ \ Id\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -\ A\ compressed\ summary\ of\ the\ previous\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 4\ keywords.\n\ \ \ \ \ \ \ Header\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -\ Similar\ to\ Id\ but\ includes\ the\ full\ URL.\n\ \ \ \ \ svn:executable\ -\ If\ present,\ make\ the\ file\ executable.\ \ Use\n\ \ \ \ \ \ \ 'svn\ propdel\ svn:executable\ PATH...'\ to\ clear.\n\ \ \ \ \ svn:eol-style\ \ -\ One\ of\ 'native',\ 'LF',\ 'CR',\ 'CRLF'.\n\ \ \ \ \ svn:mime-type\ \ -\ The\ mimetype\ of\ the\ file.\ \ Used\ to\ determine\n\ \ \ \ \ \ \ whether\ to\ merge\ the\ file,\ and\ how\ to\ serve\ it\ from\ Apache.\n\ \ \ \ \ \ \ A\ mimetype\ beginning\ with\ 'text/'\ (or\ an\ absent\ mimetype)\ is\n\ \ \ \ \ \ \ treated\ as\ text.\ \ Anything\ else\ is\ treated\ as\ binary.\n\ \ \ \ \ svn:externals\ \ -\ A\ newline\ separated\ list\ of\ module\ specifiers,\n\ \ \ \ \ \ \ each\ of\ which\ consists\ of\ a\ relative\ directory\ path,\ optional\n\ \ \ \ \ \ \ revision\ flags\ and\ an\ URL.\ \ The\ ordering\ of\ the\ three\ elements\n\ \ \ \ \ \ \ implements\ different\ behavior.\ \ Subversion\ 1.4\ and\ earlier\ only\n\ \ \ \ \ \ \ support\ the\ following\ formats\ and\ the\ URLs\ cannot\ have\ peg\n\ \ \ \ \ \ \ revisions:\n\ \ \ \ \ \ \ \ \ foo\ \ \ \ \ \ \ \ \ \ \ \ \ http://example.com/repos/zig\n\ \ \ \ \ \ \ \ \ foo/bar\ -r\ 1234\ http://example.com/repos/zag\n\ \ \ \ \ \ \ Subversion\ 1.5\ and\ greater\ support\ the\ above\ formats\ and\ the\n\ \ \ \ \ \ \ following\ formats\ where\ the\ URLs\ may\ have\ peg\ revisions:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ http://example.com/repos/zig\ foo\n\ \ \ \ \ \ \ \ \ -r\ 1234\ http://example.com/repos/zig\ foo/bar\n\ \ \ \ \ \ \ Relative\ URLs\ are\ supported\ in\ Subversion\ 1.5\ and\ greater\ for\n\ \ \ \ \ \ \ all\ above\ formats\ and\ are\ indicated\ by\ starting\ the\ URL\ with\ one\n\ \ \ \ \ \ \ of\ the\ following\ strings\n\ \ \ \ \ \ \ \ \ ../\ \ to\ the\ parent\ directory\ of\ the\ extracted\ external\n\ \ \ \ \ \ \ \ \ ^/\ \ \ to\ the\ repository\ root\n\ \ \ \ \ \ \ \ \ //\ \ \ to\ the\ scheme\n\ \ \ \ \ \ \ \ \ /\ \ \ \ to\ the\ server\ root\n\ \ \ \ \ \ \ The\ ambiguous\ format\ 'relative_path\ relative_path'\ is\ taken\ as\n\ \ \ \ \ \ \ 'relative_url\ relative_path'\ with\ peg\ revision\ support.\n\ \ \ \ \ svn:needs-lock\ -\ If\ present,\ indicates\ that\ the\ file\ should\ be\ locked\n\ \ \ \ \ \ \ before\ it\ is\ modified.\ \ Makes\ the\ working\ copy\ file\ read-only\n\ \ \ \ \ \ \ when\ it\ is\ not\ locked.\ \ Use\ 'svn\ propdel\ svn:needs-lock\ PATH...'\n\ \ \ \ \ \ \ to\ clear.\n\ \n\ \ \ The\ svn:keywords,\ svn:executable,\ svn:eol-style,\ svn:mime-type\ and\n\ \ \ svn:needs-lock\ properties\ cannot\ be\ set\ on\ a\ directory.\ \ A\ non-recursive\n\ \ \ attempt\ will\ fail,\ and\ a\ recursive\ attempt\ will\ set\ the\ property\n\ \ \ only\ on\ the\ file\ children\ of\ the\ directory. propdel.description=\ Remove\ a\ property\ from\ files,\ dirs,\ or\ revisions.\n\ usage:\ 1.\ propdel\ PROPNAME\ [PATH...]\n\ \ \ \ \ \ \ \ 2.\ propdel\ PROPNAME\ --revprop\ -r\ REV\ [TARGET]\n\ \n\ \ \ 1.\ Removes\ versioned\ props\ in\ working\ copy.\n\ \ \ 2.\ Removes\ unversioned\ remote\ prop\ on\ repos\ revision.\n\ \ \ \ \ \ TARGET\ only\ determines\ which\ repository\ to\ access. propedit.description=\ Edit\ a\ property\ with\ an\ external\ editor.\n\ usage:\ 1.\ propedit\ PROPNAME\ TARGET...\n\ \ \ \ \ \ \ \ 2.\ propedit\ PROPNAME\ --revprop\ -r\ REV\ [TARGET]\n\ \n\ \ \ 1.\ Edits\ versioned\ prop\ in\ working\ copy\ or\ repository.\n\ \ \ 2.\ Edits\ unversioned\ remote\ prop\ on\ repos\ revision.\n\ \ \ \ \ \ TARGET\ only\ determines\ which\ repository\ to\ access.\n\ \n\ See\ 'jsvn\ help\ propset'\ for\ more\ on\ setting\ properties. merge.description=\ Apply\ the\ differences\ between\ two\ sources\ to\ a\ working\ copy\ path.\n\ usage:\ 1.\ merge\ sourceURL1[@N]\ sourceURL2[@M]\ [WCPATH]\n\ \ \ \ \ \ \ \ 2.\ merge\ sourceWCPATH1@N\ sourceWCPATH2@M\ [WCPATH]\n\ \ \ \ \ \ \ \ 3.\ merge\ [-c\ M[,N...]\ |\ -r\ N:M\ ...]\ SOURCE[@REV]\ [WCPATH]\n\ \n\ \ \ 1.\ In\ the\ first\ form,\ the\ source\ URLs\ are\ specified\ at\ revisions\n\ \ \ \ \ \ N\ and\ M.\ \ These\ are\ the\ two\ sources\ to\ be\ compared.\ \ The\ revisions\n\ \ \ \ \ \ default\ to\ HEAD\ if\ omitted.\n\ \n\ \ \ 2.\ In\ the\ second\ form,\ the\ URLs\ corresponding\ to\ the\ source\ working\n\ \ \ \ \ \ copy\ paths\ define\ the\ sources\ to\ be\ compared.\ \ The\ revisions\ must\n\ \ \ \ \ \ be\ specified.\n\ \n\ \ \ 3.\ In\ the\ third\ form,\ SOURCE\ can\ be\ either\ a\ URL\ or\ a\ working\ copy\n\ \ \ \ \ \ path\ (in\ which\ case\ its\ corresponding\ URL\ is\ used).\ \ SOURCE\ (in\n\ \ \ \ \ \ revision\ REV)\ is\ compared\ as\ it\ existed\ between\ revisions\ N\ and\ M\n\ \ \ \ \ \ for\ each\ revision\ range\ provided.\ \ If\ REV\ is\ not\ specified,\ HEAD\n\ \ \ \ \ \ is\ assumed.\ \ '-c\ M'\ is\ equivalent\ to\ '-r\ :M',\ and\ '-c\ -M'\n\ \ \ \ \ \ does\ the\ reverse:\ '-r\ M:'.\ \ If\ no\ revision\ ranges\ are\n\ \ \ \ \ \ specified,\ the\ default\ range\ of\ 0:REV\ is\ used.\ \ Multiple\ '-c'\n\ \ \ \ \ \ and/or\ '-r'\ options\ may\ be\ specified,\ and\ mixing\ of\ forward\n\ \ \ \ \ \ and\ reverse\ ranges\ is\ allowed.\n\ \n\ \ \ WCPATH\ is\ the\ working\ copy\ path\ that\ will\ receive\ the\ changes.\n\ \ \ If\ WCPATH\ is\ omitted,\ a\ default\ value\ of\ '.'\ is\ assumed,\ unless\n\ \ \ the\ sources\ have\ identical\ basenames\ that\ match\ a\ file\ within\ '.':\n\ \ \ in\ which\ case,\ the\ differences\ will\ be\ applied\ to\ that\ file.\n\ \n\ \ \ NOTE:\ \ Subversion\ will\ only\ record\ metadata\ to\ track\ the\ merge\n\ \ \ if\ the\ two\ sources\ are\ on\ the\ same\ line\ of\ history\ --\ if\ the\n\ \ \ first\ source\ is\ an\ ancestor\ of\ the\ second,\ or\ vice-versa.\ \ This\ is\n\ \ \ guaranteed\ to\ be\ the\ case\ when\ using\ the\ third\ form\ listed\ above.\n\ \ \ The\ --ignore-ancestry\ option\ overrides\ this,\ forcing\ Subversion\ to\n\ \ \ regard\ the\ sources\ as\ unrelated\ and\ not\ to\ track\ the\ merge. update.description=\ Bring\ changes\ from\ the\ repository\ into\ the\ working\ copy.\n\ usage:\ update\ [PATH...]\n\ \n\ \ \ If\ no\ revision\ is\ given,\ bring\ working\ copy\ up-to-date\ with\ HEAD\ rev.\n\ \ \ Else\ synchronize\ working\ copy\ to\ revision\ given\ by\ -r.\n\ \n\ \ \ For\ each\ updated\ item\ a\ line\ will\ start\ with\ a\ character\ reporting\ the\n\ \ \ action\ taken.\ \ These\ characters\ have\ the\ following\ meaning:\n\ \n\ \ \ \ \ A\ \ Added\n\ \ \ \ \ D\ \ Deleted\n\ \ \ \ \ U\ \ Updated\n\ \ \ \ \ C\ \ Conflict\n\ \ \ \ \ G\ \ Merged\n\ \ \ \ \ E\ \ Existed\n\ \n\ \ \ A\ character\ in\ the\ first\ column\ signifies\ an\ update\ to\ the\ actual\ file,\n\ \ \ while\ updates\ to\ the\ file's\ properties\ are\ shown\ in\ the\ second\ column.\n\ \ \ A\ 'B'\ in\ the\ third\ column\ signifies\ that\ the\ lock\ for\ the\ file\ has\n\ \ \ been\ broken\ or\ stolen.\n\ \n\ \ \ If\ --force\ is\ used,\ unversioned\ obstructing\ paths\ in\ the\ working\n\ \ \ copy\ do\ not\ automatically\ cause\ a\ failure\ if\ the\ update\ attempts\ to\n\ \ \ add\ the\ same\ path.\ \ If\ the\ obstructing\ path\ is\ the\ same\ type\ (file\n\ \ \ or\ directory)\ as\ the\ corresponding\ path\ in\ the\ repository\ it\ becomes\n\ \ \ versioned\ but\ its\ contents\ are\ left\ 'as-is'\ in\ the\ working\ copy.\n\ \ \ This\ means\ that\ an\ obstructing\ directory's\ unversioned\ children\ may\n\ \ \ also\ obstruct\ and\ become\ versioned.\ \ For\ files,\ any\ content\ differences\n\ \ \ between\ the\ obstruction\ and\ the\ repository\ are\ treated\ like\ a\ local\n\ \ \ modification\ to\ the\ working\ copy.\ \ All\ properties\ from\ the\ repository\n\ \ \ are\ applied\ to\ the\ obstructing\ path.\ \ Obstructing\ paths\ are\ reported\n\ \ \ in\ the\ first\ column\ with\ code\ 'E'.\n\ \n\ \ \ Use\ the\ --set-depth\ option\ to\ set\ a\ new\ working\ copy\ depth\ on\ the\n\ \ \ targets\ of\ this\ operation.\ \ Currently,\ the\ depth\ of\ a\ working\ copy\n\ \ \ directory\ can\ only\ be\ increased\ (telescoped\ more\ deeply);\ you\ cannot\n\ \ \ make\ a\ directory\ more\ shallow. checkout.description=\ Check\ out\ a\ working\ copy\ from\ a\ repository.\n\ usage:\ checkout\ URL[@REV]...\ [PATH]\n\ \n\ \ \ If\ specified,\ REV\ determines\ in\ which\ revision\ the\ URL\ is\ first\n\ \ \ looked\ up.\n\ \n\ \ \ If\ PATH\ is\ omitted,\ the\ basename\ of\ the\ URL\ will\ be\ used\ as\n\ \ \ the\ destination.\ If\ multiple\ URLs\ are\ given\ each\ will\ be\ checked\n\ \ \ out\ into\ a\ sub-directory\ of\ PATH,\ with\ the\ name\ of\ the\ sub-directory\n\ \ \ being\ the\ basename\ of\ the\ URL.\n\ \n\ \ \ If\ --force\ is\ used,\ unversioned\ obstructing\ paths\ in\ the\ working\n\ \ \ copy\ destination\ do\ not\ automatically\ cause\ the\ check\ out\ to\ fail.\n\ \ \ If\ the\ obstructing\ path\ is\ the\ same\ type\ (file\ or\ directory)\ as\ the\n\ \ \ corresponding\ path\ in\ the\ repository\ it\ becomes\ versioned\ but\ its\n\ \ \ contents\ are\ left\ 'as-is'\ in\ the\ working\ copy.\ \ This\ means\ that\ an\n\ \ \ obstructing\ directory's\ unversioned\ children\ may\ also\ obstruct\ and\n\ \ \ become\ versioned.\ \ For\ files,\ any\ content\ differences\ between\ the\n\ \ \ obstruction\ and\ the\ repository\ are\ treated\ like\ a\ local\ modification\n\ \ \ to\ the\ working\ copy.\ \ All\ properties\ from\ the\ repository\ are\ applied\n\ \ \ to\ the\ obstructing\ path.\n\ \n\ \ \ See\ also\ 'svn\ help\ update'\ for\ a\ list\ of\ possible\ characters\n\ \ \ reporting\ the\ action\ taken. export.description=\ Create\ an\ unversioned\ copy\ of\ a\ tree.\n\ usage:\ 1.\ export\ [-r\ REV]\ URL[@PEGREV]\ [PATH]\n\ \ \ \ \ \ \ \ 2.\ export\ [-r\ REV]\ PATH1[@PEGREV]\ [PATH2]\n\ \n\ \ \ 1.\ Exports\ a\ clean\ directory\ tree\ from\ the\ repository\ specified\ by\n\ \ \ \ \ \ URL,\ at\ revision\ REV\ if\ it\ is\ given,\ otherwise\ at\ HEAD,\ into\n\ \ \ \ \ \ PATH.\ If\ PATH\ is\ omitted,\ the\ last\ component\ of\ the\ URL\ is\ used\n\ \ \ \ \ \ for\ the\ local\ directory\ name.\n\ \n\ \ \ 2.\ Exports\ a\ clean\ directory\ tree\ from\ the\ working\ copy\ specified\ by\n\ \ \ \ \ \ PATH1,\ at\ revision\ REV\ if\ it\ is\ given,\ otherwise\ at\ WORKING,\ into\n\ \ \ \ \ \ PATH2.\ \ If\ PATH2\ is\ omitted,\ the\ last\ component\ of\ the\ PATH1\ is\ used\n\ \ \ \ \ \ for\ the\ local\ directory\ name.\ If\ REV\ is\ not\ specified,\ all\ local\n\ \ \ \ \ \ changes\ will\ be\ preserved.\ \ Files\ not\ under\ version\ control\ will\n\ \ \ \ \ \ not\ be\ copied.\n\ \n\ \ \ If\ specified,\ PEGREV\ determines\ in\ which\ revision\ the\ target\ is\ first\n\ \ \ looked\ up. switch.description=\ Update\ the\ working\ copy\ to\ a\ different\ URL.\n\ usage:\ 1.\ switch\ URL[@PEGREV]\ [PATH]\n\ \ \ \ \ \ \ \ 2.\ switch\ --relocate\ FROM\ TO\ [PATH...]\n\ \n\ \ \ 1.\ Update\ the\ working\ copy\ to\ mirror\ a\ new\ URL\ within\ the\ repository.\n\ \ \ \ \ \ This\ behavior\ is\ similar\ to\ 'svn\ update',\ and\ is\ the\ way\ to\n\ \ \ \ \ \ move\ a\ working\ copy\ to\ a\ branch\ or\ tag\ within\ the\ same\ repository.\n\ \ \ \ \ \ If\ specified,\ PEGREV\ determines\ in\ which\ revision\ the\ target\ is\ first\n\ \ \ \ \ \ looked\ up.\n\ \n\ \ \ \ \ \ If\ --force\ is\ used,\ unversioned\ obstructing\ paths\ in\ the\ working\n\ \ \ \ \ \ copy\ do\ not\ automatically\ cause\ a\ failure\ if\ the\ switch\ attempts\ to\n\ \ \ \ \ \ add\ the\ same\ path.\ \ If\ the\ obstructing\ path\ is\ the\ same\ type\ (file\n\ \ \ \ \ \ or\ directory)\ as\ the\ corresponding\ path\ in\ the\ repository\ it\ becomes\n\ \ \ \ \ \ versioned\ but\ its\ contents\ are\ left\ 'as-is'\ in\ the\ working\ copy.\n\ \ \ \ \ \ This\ means\ that\ an\ obstructing\ directory's\ unversioned\ children\ may\n\ \ \ \ \ \ also\ obstruct\ and\ become\ versioned.\ \ For\ files,\ any\ content\ differences\n\ \ \ \ \ \ between\ the\ obstruction\ and\ the\ repository\ are\ treated\ like\ a\ local\n\ \ \ \ \ \ modification\ to\ the\ working\ copy.\ \ All\ properties\ from\ the\ repository\n\ \ \ \ \ \ are\ applied\ to\ the\ obstructing\ path.\n\ \n\ \ \ \ \ \ Use\ the\ --set-depth\ option\ to\ set\ a\ new\ working\ copy\ depth\ on\ the\n\ \ \ \ \ \ targets\ of\ this\ operation.\ \ Currently,\ the\ depth\ of\ a\ working\ copy\n\ \ \ \ \ \ directory\ can\ only\ be\ increased\ (telescoped\ more\ deeply);\ you\ cannot\n\ \ \ \ \ \ make\ a\ directory\ more\ shallow.\n\ \n\ \ \ 2.\ Rewrite\ working\ copy\ URL\ metadata\ to\ reflect\ a\ syntactic\ change\ only.\n\ \ \ \ \ \ This\ is\ used\ when\ repository's\ root\ URL\ changes\ (such\ as\ a\ scheme\n\ \ \ \ \ \ or\ hostname\ change)\ but\ your\ working\ copy\ still\ reflects\ the\ same\n\ \ \ \ \ \ directory\ within\ the\ same\ repository.\n\ \n\ \ \ See\ also\ 'svn\ help\ update'\ for\ a\ list\ of\ possible\ characters\n\ \ \ reporting\ the\ action\ taken. import.description=\ Commit\ an\ unversioned\ file\ or\ tree\ into\ the\ repository.\n\ usage:\ import\ [PATH]\ URL\n\ \n\ \ \ Recursively\ commit\ a\ copy\ of\ PATH\ to\ URL.\n\ \ \ If\ PATH\ is\ omitted\ '.'\ is\ assumed.\n\ \ \ Parent\ directories\ are\ created\ as\ necessary\ in\ the\ repository.\n\ \ \ If\ PATH\ is\ a\ directory,\ the\ contents\ of\ the\ directory\ are\ added\n\ \ \ directly\ under\ URL.\n\ \ \ Unversionable\ items\ such\ as\ device\ files\ and\ pipes\ are\ ignored\n\ \ \ if\ --force\ is\ specified. commit.description=\ Send\ changes\ from\ your\ working\ copy\ to\ the\ repository.\n\ usage:\ commit\ [PATH...]\n\ \n\ \ \ A\ log\ message\ must\ be\ provided,\ but\ it\ can\ be\ empty.\ \ If\ it\ is\ not\n\ \ \ given\ by\ a\ --message\ or\ --file\ option,\ an\ editor\ will\ be\ started.\n\ \ \ If\ any\ targets\ are\ (or\ contain)\ locked\ items,\ those\ will\ be\n\ \ \ unlocked\ after\ a\ successful\ commit. mkdir.description=\ Create\ a\ new\ directory\ under\ version\ control.\n\ usage:\ 1.\ mkdir\ PATH...\n\ \ \ \ \ \ \ \ 2.\ mkdir\ URL...\n\ \n\ \ \ Create\ version\ controlled\ directories.\n\ \n\ \ \ 1.\ Each\ directory\ specified\ by\ a\ working\ copy\ PATH\ is\ created\ locally\n\ \ \ \ \ and\ scheduled\ for\ addition\ upon\ the\ next\ commit.\n\ \n\ \ \ 2.\ Each\ directory\ specified\ by\ a\ URL\ is\ created\ in\ the\ repository\ via\n\ \ \ \ \ an\ immediate\ commit.\n\ \n\ \ \ In\ both\ cases,\ all\ the\ intermediate\ directories\ must\ already\ exist,\n\ \ \ unless\ the\ --parents\ option\ is\ given. add.description=\ Put\ files\ and\ directories\ under\ version\ control,\ scheduling\n\ them\ for\ addition\ to\ repository.\ \ They\ will\ be\ added\ in\ next\ commit.\n\ usage:\ add\ PATH... delete.description=\ Remove\ files\ and\ directories\ from\ version\ control.\n\ usage:\ 1.\ delete\ PATH...\n\ \ \ \ \ \ \ \ 2.\ delete\ URL...\n\ \n\ \ \ 1.\ Each\ item\ specified\ by\ a\ PATH\ is\ scheduled\ for\ deletion\ upon\n\ \ \ \ \ the\ next\ commit.\ \ Files,\ and\ directories\ that\ have\ not\ been\n\ \ \ \ \ committed,\ are\ immediately\ removed\ from\ the\ working\ copy\n\ \ \ \ \ unless\ the\ --keep-local\ option\ is\ given.\n\ \ \ \ \ PATHs\ that\ are,\ or\ contain,\ unversioned\ or\ modified\ items\ will\n\ \ \ \ \ not\ be\ removed\ unless\ the\ --force\ option\ is\ given.\n\ \n\ \ \ 2.\ Each\ item\ specified\ by\ a\ URL\ is\ deleted\ from\ the\ repository\n\ \ \ \ \ via\ an\ immediate\ commit. revert.description=\ Restore\ pristine\ working\ copy\ file\ (undo\ most\ local\ edits).\n\ usage:\ revert\ PATH...\n\ \n\ \ \ Note:\ \ this\ subcommand\ does\ not\ require\ network\ access,\ and\ resolves\n\ \ \ any\ conflicted\ states.\ \ However,\ it\ does\ not\ restore\ removed\ directories. lock.description=\ Lock\ working\ copy\ paths\ or\ URLs\ in\ the\ repository,\ so\ that\n\ no\ other\ user\ can\ commit\ changes\ to\ them.\n\ usage:\ lock\ TARGET...\n\ \n\ \ \ Use\ --force\ to\ steal\ the\ lock\ from\ another\ user\ or\ working\ copy. unlock.description=\ Unlock\ working\ copy\ paths\ or\ URLs.\n\ usage:\ unlock\ TARGET...\n\ \n\ \ \ Use\ --force\ to\ break\ the\ lock. resolved.description=\ Remove\ 'conflicted'\ state\ on\ working\ copy\ files\ or\ directories.\n\ usage:\ resolved\ PATH...\n\ \n\ \ \ Note:\ \ this\ subcommand\ does\ not\ semantically\ resolve\ conflicts\ or\n\ \ \ remove\ conflict\ markers;\ it\ merely\ removes\ the\ conflict-related\n\ \ \ artifact\ files\ and\ allows\ PATH\ to\ be\ committed\ again.\ \ It\ has\ been\n\ \ \ deprecated\ in\ favor\ of\ running\ 'svn\ resolve\ --accept\ working'. resolve.description=\ Resolve\ conflicts\ on\ working\ copy\ files\ or\ directories.\n\ usage:\ resolve\ --accept=ARG\ [PATH...]\n\ \n\ \ \ Note:\ \ the\ --accept\ option\ is\ currently\ required. cleanup.description=\ Recursively\ clean\ up\ the\ working\ copy,\ removing\ locks,\ resuming\n\ unfinished\ operations,\ etc.\n\ usage:\ cleanup\ [PATH...] move.description=\ Move\ and/or\ rename\ something\ in\ working\ copy\ or\ repository.\n\ usage:\ move\ SRC...\ DST\n\ \n\ When\ moving\ multiple\ sources,\ they\ will\ be\ added\ as\ children\ of\ DST,\n\ which\ must\ be\ a\ directory.\n\ \n\ \ \ Note:\ \ this\ subcommand\ is\ equivalent\ to\ a\ 'copy'\ and\ 'delete'.\n\ \ \ Note:\ \ the\ --revision\ option\ has\ no\ use\ and\ is\ deprecated.\n\ \n\ \ \ SRC\ and\ DST\ can\ both\ be\ working\ copy\ (WC)\ paths\ or\ URLs:\n\ \ \ \ \ WC\ \ ->\ WC:\ \ \ move\ and\ schedule\ for\ addition\ (with\ history)\n\ \ \ \ \ URL\ ->\ URL:\ \ complete\ server-side\ rename.\n\ \ \ All\ the\ SRCs\ must\ be\ of\ the\ same\ type. copy.description=\ Duplicate\ something\ in\ working\ copy\ or\ repository,\ remembering\n\ history.\n\ usage:\ copy\ SRC[@REV]...\ DST\n\ \n\ When\ copying\ multiple\ sources,\ they\ will\ be\ added\ as\ children\ of\ DST,\n\ which\ must\ be\ a\ directory.\n\ \n\ \ \ SRC\ and\ DST\ can\ each\ be\ either\ a\ working\ copy\ (WC)\ path\ or\ URL:\n\ \ \ \ \ WC\ \ ->\ WC:\ \ \ copy\ and\ schedule\ for\ addition\ (with\ history)\n\ \ \ \ \ WC\ \ ->\ URL:\ \ immediately\ commit\ a\ copy\ of\ WC\ to\ URL\n\ \ \ \ \ URL\ ->\ WC:\ \ \ check\ out\ URL\ into\ WC,\ schedule\ for\ addition\n\ \ \ \ \ URL\ ->\ URL:\ \ complete\ server-side\ copy;\ \ used\ to\ branch\ and\ tag\n\ \ \ All\ the\ SRCs\ must\ be\ of\ the\ same\ type.\n\ \n\ WARNING:\ For\ compatibility\ with\ previous\ versions\ of\ Subversion,\n\ copies\ performed\ using\ two\ working\ copy\ paths\ (WC\ ->\ WC)\ will\ not\n\ contact\ the\ repository.\ \ As\ such,\ they\ may\ not,\ by\ default,\ be\ able\n\ to\ propagate\ merge\ tracking\ information\ from\ the\ source\ of\ the\ copy\n\ to\ the\ destination. changelist.description=\ Associate\ (or\ dissociate)\ changelist\ CLNAME\ with\ the\ named\ files.\n\ usage:\ 1.\ changelist\ CLNAME\ TARGET...\n\ \ \ \ \ \ \ \ 2.\ changelist\ --remove\ TARGET... cat.description=\ Output\ the\ content\ of\ specified\ files\ or\ URLs.\n\ usage:\ cat\ TARGET[@REV]...\n\ \n\ \ \ If\ specified,\ REV\ determines\ in\ which\ revision\ the\ target\ is\ first\n\ \ \ looked\ up. blame.description=\ Output\ the\ content\ of\ specified\ files\ or\n\ URLs\ with\ revision\ and\ author\ information\ in-line.\n\ usage:\ blame\ TARGET[@REV]...\n\ \n\ \ \ If\ specified,\ REV\ determines\ in\ which\ revision\ the\ target\ is\ first\n\ \ \ looked\ up. diff.description=\ Display\ the\ differences\ between\ two\ revisions\ or\ paths.\n\ usage:\ 1.\ diff\ [-c\ M\ |\ -r\ N[:M]]\ [TARGET[@REV]...]\n\ \ \ \ \ \ \ \ 2.\ diff\ [-r\ N[:M]]\ --old=OLD-TGT[@OLDREV]\ [--new=NEW-TGT[@NEWREV]]\ \\\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ [PATH...]\n\ \ \ \ \ \ \ \ 3.\ diff\ OLD-URL[@OLDREV]\ NEW-URL[@NEWREV]\n\ \n\ \ \ 1.\ Display\ the\ changes\ made\ to\ TARGETs\ as\ they\ are\ seen\ in\ REV\ between\n\ \ \ \ \ \ two\ revisions.\ \ TARGETs\ may\ be\ all\ working\ copy\ paths\ or\ all\ URLs.\n\ \ \ \ \ \ If\ TARGETs\ are\ working\ copy\ paths,\ N\ defaults\ to\ BASE\ and\ M\ to\ the\n\ \ \ \ \ \ working\ copy;\ if\ URLs,\ N\ must\ be\ specified\ and\ M\ defaults\ to\ HEAD.\n\ \ \ \ \ \ The\ '-c\ M'\ option\ is\ equivalent\ to\ '-r\ N:M'\ where\ N\ =\ M-1.\n\ \ \ \ \ \ Using\ '-c\ -M'\ does\ the\ reverse:\ '-r\ M:N'\ where\ N\ =\ M-1.\n\ \n\ \ \ 2.\ Display\ the\ differences\ between\ OLD-TGT\ as\ it\ was\ seen\ in\ OLDREV\ and\n\ \ \ \ \ \ NEW-TGT\ as\ it\ was\ seen\ in\ NEWREV.\ \ PATHs,\ if\ given,\ are\ relative\ to\n\ \ \ \ \ \ OLD-TGT\ and\ NEW-TGT\ and\ restrict\ the\ output\ to\ differences\ for\ those\n\ \ \ \ \ \ paths.\ \ OLD-TGT\ and\ NEW-TGT\ may\ be\ working\ copy\ paths\ or\ URL[@REV].\n\ \ \ \ \ \ NEW-TGT\ defaults\ to\ OLD-TGT\ if\ not\ specified.\ \ -r\ N\ makes\ OLDREV\ default\n\ \ \ \ \ \ to\ N,\ -r\ N:M\ makes\ OLDREV\ default\ to\ N\ and\ NEWREV\ default\ to\ M.\n\ \n\ \ \ 3.\ Shorthand\ for\ 'svn\ diff\ --old=OLD-URL[@OLDREV]\ --new=NEW-URL[@NEWREV]'\n\ \n\ \ \ Use\ just\ 'svn\ diff'\ to\ display\ local\ modifications\ in\ a\ working\ copy. log.description=\ Show\ the\ log\ messages\ for\ a\ set\ of\ revision(s)\ and/or\ file(s).\n\ usage:\ 1.\ log\ [PATH]\n\ \ \ \ \ \ \ \ 2.\ log\ URL[@REV]\ [PATH...]\n\ \n\ \ \ 1.\ Print\ the\ log\ messages\ for\ a\ local\ PATH\ (default:\ '.').\n\ \ \ \ \ \ The\ default\ revision\ range\ is\ BASE:1.\n\ \n\ \ \ 2.\ Print\ the\ log\ messages\ for\ the\ PATHs\ (default:\ '.')\ under\ URL.\n\ \ \ \ \ \ If\ specified,\ REV\ determines\ in\ which\ revision\ the\ URL\ is\ first\n\ \ \ \ \ \ looked\ up,\ and\ the\ default\ revision\ range\ is\ REV:1;\ otherwise,\n\ \ \ \ \ \ the\ URL\ is\ looked\ up\ in\ HEAD,\ and\ the\ default\ revision\ range\ is\n\ \ \ \ \ \ HEAD:1.\n\ \n\ \ \ Multiple\ '-c'\ or\ '-r'\ options\ may\ be\ specified\ (but\ not\ a\n\ \ \ combination\ of\ '-c'\ and\ '-r'\ options),\ and\ mixing\ of\ forward\ and\n\ \ \ reverse\ ranges\ is\ allowed.\n\ \n\ \ \ With\ -v,\ also\ print\ all\ affected\ paths\ with\ each\ log\ message.\n\ \ \ With\ -q,\ don't\ print\ the\ log\ message\ body\ itself\ (note\ that\ this\ is\n\ \ \ compatible\ with\ -v).\n\ \n\ \ \ Each\ log\ message\ is\ printed\ just\ once,\ even\ if\ more\ than\ one\ of\ the\n\ \ \ affected\ paths\ for\ that\ revision\ were\ explicitly\ requested.\ \ Logs\n\ \ \ follow\ copy\ history\ by\ default.\ \ Use\ --stop-on-copy\ to\ disable\ this\n\ \ \ behavior,\ which\ can\ be\ useful\ for\ determining\ branchpoints.\n\ \n\ \ \ Examples:\n\ \ \ \ \ svn\ log\n\ \ \ \ \ svn\ log\ foo.c\n\ \ \ \ \ svn\ log\ http://www.example.com/repo/project/foo.c\n\ \ \ \ \ svn\ log\ http://www.example.com/repo/project\ foo.c\ bar.c list.description=\ List\ directory\ entries\ in\ the\ repository.\n\ usage:\ list\ [TARGET[@REV]...]\n\ \n\ \ \ List\ each\ TARGET\ file\ and\ the\ contents\ of\ each\ TARGET\ directory\ as\n\ \ \ they\ exist\ in\ the\ repository.\ \ If\ TARGET\ is\ a\ working\ copy\ path,\ the\n\ \ \ corresponding\ repository\ URL\ will\ be\ used.\ If\ specified,\ REV\ determines\n\ \ \ in\ which\ revision\ the\ target\ is\ first\ looked\ up.\n\ \n\ \ \ The\ default\ TARGET\ is\ '.',\ meaning\ the\ repository\ URL\ of\ the\ current\n\ \ \ working\ directory.\n\ \n\ \ \ With\ --verbose,\ the\ following\ fields\ will\ be\ shown\ for\ each\ item:\n\ \n\ \ \ \ \ Revision\ number\ of\ the\ last\ commit\n\ \ \ \ \ Author\ of\ the\ last\ commit\n\ \ \ \ \ If\ locked,\ the\ letter\ 'O'.\ \ (Use\ 'svn\ info\ URL'\ to\ see\ details)\n\ \ \ \ \ Size\ (in\ bytes)\n\ \ \ \ \ Date\ and\ time\ of\ the\ last\ commit info.description=\ Display\ information\ about\ a\ local\ or\ remote\ item.\n\ usage:\ info\ [TARGET[@REV]...]\n\ \n\ \ \ Print\ information\ about\ each\ TARGET\ (default:\ '.').\n\ \ \ TARGET\ may\ be\ either\ a\ working-copy\ path\ or\ URL.\ \ If\ specified,\ REV\n\ \ \ determines\ in\ which\ revision\ the\ target\ is\ first\ looked\ up. mergeinfo.description=\ Display\ merge-related\ information.\n\ usage:\ mergeinfo\ SOURCE[@REV]\ [TARGET[@REV]]\n\ \n\ \ \ Display\ information\ related\ to\ merges\ (or\ potential\ merges)\ between\n\ \ \ SOURCE\ and\ TARGET\ (default:\ '.').\ \ If\ the\ --show-revs\ option\n\ \ \ is\ not\ provided,\ display\ revisions\ which\ have\ been\ merged\ from\n\ \ \ SOURCE\ to\ TARGET;\ otherwise,\ display\ the\ type\ of\ information\n\ \ \ specified\ by\ the\ --show-revs\ option. upgrade.description=\ Upgrade\ the\ metadata\ storage\ format\ for\ a\ working\ copy.\n\ usage:\ upgrade\ [WCPATH...]\n\ \n\ \ \ Local\ modifications\ are\ preserved.svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svn/options.properties000066400000000000000000000174001177510526000323700ustar00rootroot00000000000000regexp=print\ out\ only\ revisions\ with\ log\ messages\ satisfying\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ this\ pattern author=print\ only\ revisions\ committed\ by\ this\ author verbose=print\ extra\ information show-updates=display\ update\ information non-recursive=obsolete;\ try\ --depth=files\ or\ --depth=immediates depth=limit\ operation\ by\ depth\ ARG\ ('empty',\ 'files',\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'immediates',\ or\ 'infinity') quiet=print\ nothing,\ or\ only\ summary\ information no-ignore=disregard\ default\ and\ svn:ignore\ property\ ignores incremental=give\ output\ suitable\ for\ concatenation xml=output\ in\ XML config-dir=read\ user\ configuration\ files\ from\ directory\ ARG config-option=set\ user\ configuration\ option\ in\ the\ format:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ FILE:SECTION:OPTION=[VALUE]\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ For example:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ servers:global:http-library=serf trust-server-cert=accept\ unknown\ SSL\ server\ certificates\ without\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ prompting\ (but\ only\ with\ '--non-interactive') ignore-externals=ignore\ externals\ definitions changelist=operate\ only\ on\ members\ of\ changelist\ ARG\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ [aliases:\ --cl] username=specify\ a\ username\ ARG password=specify\ a\ password\ ARG no-auth-cache=do\ not\ cache\ authentication\ tokens non-interactive=do\ no\ interactive\ prompting help=show\ help\ on\ a\ subcommand version=show\ program\ version\ information recursive=descend\ recursively,\ same\ as\ --depth=infinity revision=\ ARG\ (some\ commands\ also\ take\ ARG1:ARG2\ range)\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ A\ revision\ argument\ can\ be\ one\ of:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ NUMBER\ \ \ \ \ \ \ revision\ number\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ '{'\ DATE\ '}'\ revision\ at\ start\ of\ the\ date\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'HEAD'\ \ \ \ \ \ \ latest\ in\ repository\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'BASE'\ \ \ \ \ \ \ base\ rev\ of\ item's\ working\ copy\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'COMMITTED'\ \ last\ commit\ at\ or\ before\ BASE\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'PREV'\ \ \ \ \ \ \ revision\ just\ before\ COMMITTED revprop=operate\ on\ a\ revision\ property\ (use\ with\ -r) change=the\ change\ made\ by\ revision\ ARG\ (like\ -r\ ARG-1:ARG)\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ If\ ARG\ is\ negative\ this\ is\ like\ -r\ ARG:ARG-1 change.log=the\ change\ made\ in\ revision\ ARG strict=use\ strict\ semantics dry-run=try\ operation\ but\ make\ no\ changes file=read\ log\ message\ from\ file\ ARG file.propset=read\ property\ value\ from\ file\ ARG encoding=treat\ value\ as\ being\ in\ charset\ encoding\ ARG targets=pass\ contents\ of\ file\ ARG\ as\ additional\ args force=force\ operation\ to\ run force-log=force\ validity\ of\ log\ message\ source force-log.lock=force\ validity\ of\ lock\ comment\ source message=specify\ log\ message\ ARG with-revprop=set\ revision\ property\ ARG\ in\ new\ revision\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ using\ the\ name[=value]\ format with-revprop.log=retrieve\ revision\ property\ ARG editor-cmd=use\ ARG\ as\ external\ editor no-unlock=don't\ unlock\ the\ targets dyr-run=try\ operation\ but\ make\ no\ changes record-only=mark\ revisions\ as\ merged\ (use\ with\ -r) use-merge-history=\ use/display\ additional\ information\ from\ merge\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ history ignore-ancestry=ignore\ ancestry\ when\ calculating\ merges extensions=\ Default:\ '-u'.\ When\ Subversion\ is\ invoking\ an\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ external\ diff\ program,\ ARG\ is\ simply\ passed\ along\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ to\ the\ program.\ But\ when\ Subversion\ is\ using\ its\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ default\ internal\ diff\ implementation,\ or\ when\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Subversion\ is\ displaying\ blame\ annotations,\ ARG\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ could\ be\ any\ of\ the\ following:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -u\ (--unified):\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Output\ 3\ lines\ of\ unified\ context.\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -b\ (--ignore-space-change):\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Ignore\ changes\ in\ the\ amount\ of\ white\ space.\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -w\ (--ignore-all-space):\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Ignore\ all\ white\ space.\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ --ignore-eol-style:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Ignore\ changes\ in\ EOL\ style. native-eol=\ use\ a\ different\ EOL\ marker\ than\ the\ standard\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ system\ marker\ for\ files\ with\ the\ svn:eol-style\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ property\ set\ to\ 'native'.\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ARG\ may\ be\ one\ of\ 'LF',\ 'CR',\ 'CRLF' relocate=relocate\ via\ URL-rewriting auto-props=enable\ automatic\ properties no-auto-props=disable\ automatic\ properties keep-changelists=don't\ delete\ changelists\ after\ commit parents=make\ intermediate\ directories parents.add=add\ intermediate\ parents keep-local=keep\ path\ in\ working\ copy file.lock=read\ lock\ comment\ from\ file\ ARG message.lock=specify\ lock\ comment\ ARG accept=specify\ automatic\ conflict\ resolution\ action\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ('postpone',\ 'base',\ 'mine-conflict',\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'theirs-conflict',\ 'mine-full',\ 'theirs-full',\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'edit',\ 'launch') accept.resolved=specify\ automatic\ conflict\ resolution\ action\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ('base',\ 'mine',\ 'theirs') accept.resolve=specify\ automatic\ conflict\ resolution\ source\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ('base',\ 'working',\ 'mine-conflict',\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'theirs-conflict',\ 'mine-full',\ 'theirs-full') remove=remove\ changelist\ association old=use\ ARG\ as\ the\ older\ target new=use\ ARG\ as\ the\ newer\ target summarize=show\ a\ summary\ of\ the\ results no-diff-deleted=do\ not\ print\ differences\ for\ deleted\ files notice-ancestry=notice\ ancestry\ when\ calculating\ differences limit=maximum\ number\ of\ log\ entries stop-on-copy=do\ not\ cross\ copies\ while\ traversing\ history with-all-revprops=retrieve\ all\ revision\ properties with-no-revprops=retrieve\ no\ revision\ properties show-revs=specify\ which\ collection\ of\ revisions\ to\ display\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ('merged',\ 'eligible') reintegrate=lump-merge\ all\ of\ source\ URL's\ unmerged\ changes set-depth=set\ new\ working\ copy\ depth\ to\ ARG\ ('exclude',\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 'empty',\ 'files',\ 'immediates',\ or\ 'infinity') diff-cmd=use\ ARG\ as\ diff\ command diff3-cmd=use\ ARG\ as\ merge\ command svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnadmin/000077500000000000000000000000001177510526000275665ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnadmin/commands.properties000066400000000000000000000114731177510526000335130ustar00rootroot00000000000000pack.description=\ usage:\ jsvnadmin\ pack\ REPOS_PATH\n\n\ Possibly\ compact\ the\ repository\ into\ a\ more\ efficient\ storage\ model.\n\ This\ may\ not\ apply\ to\ all\ repositories,\ in\ which\ case,\ exit. help.description=\ usage:\ jsvnadmin\ help\ [SUBCOMMAND...]\n\n\ Describe\ the\ usage\ of\ this\ program\ or\ its\ subcommands. create.description=\ usage:\ jsvnadmin\ create\ REPOS_PATH\n\n\ Create\ a\ new,\ empty\ repository\ at\ REPOS_PATH. dump.description=\ usage:\ jsvnadmin\ dump\ REPOS_PATH\ [-r\ LOWER[:UPPER]\ [--incremental]]\n\n\ Dump\ the\ contents\ of\ filesystem\ to\ stdout\ in\ a\ 'dumpfile'\n\ portable\ format,\ sending\ feedback\ to\ stderr.\ \ Dump\ revisions\n\ LOWER\ rev\ through\ UPPER\ rev.\ \ If\ no\ revisions\ are\ given,\ dump\ all\n\ revision\ trees.\ \ If\ only\ LOWER\ is\ given,\ dump\ that\ one\ revision\ tree.\n\ If\ --incremental\ is\ passed,\ the\ first\ revision\ dumped\ will\ describe\n\ only\ the\ paths\ changed\ in\ that\ revision;\ otherwise\ it\ will\ describe\n\ every\ path\ present\ in\ the\ repository\ as\ of\ that\ revision.\ \ (In\ either\n\ case,\ the\ second\ and\ subsequent\ revisions,\ if\ any,\ describe\ only\ paths\n\ changed\ in\ those\ revisions.) load.description=\ usage:\ jsvnadmin\ load\ REPOS_PATH\n\n\ Read\ a\ 'dumpfile'-formatted\ stream\ from\ stdin,\ committing\n\ new\ revisions\ into\ the\ repository's\ filesystem.\ \ If\ the\ repository\n\ was\ previously\ empty,\ its\ UUID\ will,\ by\ default,\ be\ changed\ to\ the\n\ one\ specified\ in\ the\ stream.\ \ Progress\ feedback\ is\ sent\ to\ stdout. verify.description=\ usage:\ jsvnadmin\ verify\ REPOS_PATH\n\n\ Verifies\ the\ data\ stored\ in\ the\ repository. lslocks.description=\ usage:\ jsvnadmin\ lslocks\ REPOS_PATH\ [PATH-IN-REPOS]\n\n\ Print\ descriptions\ of\ all\ locks\ on\ or\ under\ PATH-IN-REPOS\ (which,\n\ if\ not\ provided,\ is\ the\ root\ of\ the\ repository). lstxns.description=\ usage:\ jsvnadmin\ lstxns\ REPOS_PATH\n\n\ Print\ the\ names\ of\ all\ uncommitted\ transactions. rmlocks.description=\ usage:\ jsvnadmin\ rmlocks\ REPOS_PATH\ LOCKED_PATH...\n\n\ Unconditionally\ remove\ lock\ from\ each\ LOCKED_PATH. rmtxns.description=\ usage:\ jsvnadmin\ rmtxns\ REPOS_PATH\ TXN_NAME...\n\n\ Delete\ the\ named\ transaction(s). setlog.description=\ usage:\ jsvnadmin\ setlog\ REPOS_PATH\ -r\ REVISION\ FILE\n\n\ Set\ the\ log-message\ on\ revision\ REVISION\ to\ the\ contents\ of\ FILE.\ \ Use\n\ --bypass-hooks\ to\ avoid\ triggering\ the\ revision-property-related\ hooks\n\ (for\ example,\ if\ you\ do\ not\ want\ an\ email\ notification\ sent\n\ from\ your\ post-revprop-change\ hook,\ or\ because\ the\ modification\ of\n\ revision\ properties\ has\ not\ been\ enabled\ in\ the\ pre-revprop-change\n\ hook).\n\n\ NOTE:\ Revision\ properties\ are\ not\ versioned,\ so\ this\ command\ will\n\ overwrite\ the\ previous\ log\ message. setrevprop.description=\ usage:\ jsvnadmin\ setrevprop\ REPOS_PATH\ -r\ REVISION\ NAME\ FILE\n\n\ Set\ the\ property\ NAME\ on\ revision\ REVISION\ to\ the\ contents\ of\ FILE.\ Use\n\ --use-pre-revprop-change-hook/--use-post-revprop-change-hook\ to\ trigger\n\ the\ revision\ property-related\ hooks\ (for\ example,\ if\ you\ want\ an\ email\n\ notification\ sent\ from\ your\ post-revprop-change\ hook).\n\n\ NOTE:\ Revision\ properties\ are\ not\ versioned,\ so\ this\ command\ will\n\ overwrite\ the\ previous\ value\ of\ the\ property. recover.description=\ usage:\ jsvnadmin\ recover\ REPOS_PATH\n\n\ Run\ the\ recovery\ procedure\ on\ a\ repository.\ \ Do\ this\ if\ you've\n\ been\ getting\ errors\ indicating\ that\ recovery\ ought\ to\ be\ run.\n\ Berkeley\ DB\ recovery\ requires\ exclusive\ access\ and\ will\n\ exit\ if\ the\ repository\ is\ in\ use\ by\ another\ process. upgrade.description=\ usage:\ jsvnadmin\ upgrade\ REPOS_PATH\n\n\ Upgrade\ the\ repository\ located\ at\ REPOS_PATH\ to\ the\ latest\ supported\n\ schema\ version.\n\n\ This\ functionality\ is\ provided\ as\ a\ convenience\ for\ repository\n\ administrators\ who\ wish\ to\ make\ use\ of\ new\ Subversion\ functionality\n\ without\ having\ to\ undertake\ a\ potentially\ costly\ full\ repository\ dump\n\ and\ load\ operation.\ \ As\ such,\ the\ upgrade\ performs\ only\ the\ minimum\n\ amount\ of\ work\ needed\ to\ accomplish\ this\ while\ still\ maintaining\ the\n\ integrity\ of\ the\ repository.\ \ It\ does\ not\ guarantee\ the\ most\ optimized\n\ repository\ state\ as\ a\ dump\ and\ subsequent\ load\ would. setuuid.description=\ usage:\ jsvnadmin\ setuuid\ REPOS_PATH\ [NEW_UUID]\n\n\ Reset\ the\ repository\ UUID\ for\ the\ repository\ located\ at\ REPOS_PATH.\ \ If\n\ NEW_UUID\ is\ provided,\ use\ that\ as\ the\ new\ repository\ UUID;\ otherwise,\n\ generate\ a\ brand\ new\ UUID\ for\ the\ repository. hotcopy.description=\ usage:\ jsvnadmin\ hotcopy\ REPOS_PATH\ NEW_REPOS_PATH\n\n\ Makes\ a\ hot\ copy\ of\ a\ repository.svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnadmin/options.properties000066400000000000000000000027671177510526000334130ustar00rootroot00000000000000help=show\ help\ on\ a\ subcommand version=show\ program\ version\ information config-dir=read\ user\ configuration\ files\ from\ directory\ ARG pre-1.4-compatible=use\ format\ compatible\ with\ Subversion\ versions\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ earlier\ than\ 1.4 pre-1.5-compatible=use\ format\ compatible\ with\ Subversion\ versions\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ earlier\ than\ 1.5 pre-1.6-compatible=use\ format\ compatible\ with\ Subversion\ versions\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ earlier\ than\ 1.6 revision=specify\ revision\ number\ ARG\ (or\ X:Y\ range) fs-type=only\ 'fsfs'\ repository\ format\ is\ supported\ by\ jsvnadmin incremental=dump\ incrementally deltas=use\ deltas\ in\ dump\ output quiet=no\ progress\ (only\ errors)\ to\ stderr ignore-uuid=ignore\ any\ repos\ UUID\ found\ in\ the\ stream force-uuid=set\ repos\ UUID\ to\ that\ found\ in\ stream,\ if\ any parent-dir=load\ at\ specified\ directory\ in\ repository use-pre-commit-hook=call\ pre-commit\ hook\ before\ committing\ revisions use-post-commit-hook=call\ post-commit\ hook\ after\ committing\ revisions bypass-hooks=bypass\ the\ repository\ hook\ system use-pre-revprop-change-hook=call\ hook\ before\ changing\ revision\ property use-post-revprop-change-hook=call\ hook\ after\ changing\ revision\ property wait=wait\ instead\ of\ exit\ if\ the\ repository\ is\ in\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ use\ by\ another\ processsvnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svndumpfilter/000077500000000000000000000000001177510526000306515ustar00rootroot00000000000000commands.properties000066400000000000000000000006131177510526000345110ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svndumpfilterhelp.description=Describe\ the\ usage\ of\ this\ program\ or\ its\ subcommands.\n\ usage:\ jsvndumpfilter\ help\ [SUBCOMMAND...] exclude.description=Filter\ out\ nodes\ with\ given\ prefixes\ from\ dumpstream.\n\ usage:\ jsvndumpfilter\ exclude\ PATH_PREFIX... include.description=Filter\ out\ nodes\ without\ given\ prefixes\ from\ dumpstream.\n\ usage:\ jsvndumpfilter\ include\ PATH_PREFIX...options.properties000066400000000000000000000006401177510526000344030ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svndumpfiltertargets=Pass\ contents\ of\ file\ ARG\ as\ additional\ args quiet=Do\ not\ display\ filtering\ statistics. drop-empty-revs=Remove\ revisions\ emptied\ by\ filtering. renumber-revs=Renumber\ revisions\ left\ after\ filtering. skip-missing-merge-sources=Skip\ missing\ merge\ sources. preserve-revprops=Don't\ filter\ revision\ properties. version=show\ program\ version\ information help=show\ help\ on\ a\ subcommandsvnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnlook/000077500000000000000000000000001177510526000274425ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnlook/commands.properties000066400000000000000000000047521177510526000333710ustar00rootroot00000000000000author.description=usage:\ jsvnlook\ author\ REPOS_PATH\n\n\ Print\ the\ author. cat.description=usage:\ jsvnlook\ cat\ REPOS_PATH\ FILE_PATH\n\n\ Print\ the\ contents\ of\ a\ file.\ \ Leading\ '/'\ on\ FILE_PATH\ is\ optional. changed.description=usage:\ jsvnlook\ changed\ REPOS_PATH\n\n\ Print\ the\ paths\ that\ were\ changed. date.description=usage:\ jsvnlook\ date\ REPOS_PATH\n\n\ Print\ the\ datestamp. diff.description=usage:\ jsvnlook\ diff\ REPOS_PATH\n\n\ Print\ GNU-style\ diffs\ of\ changed\ files\ and\ properties. dirs-changed.description=usage:\ jsvnlook\ dirs-changed\ REPOS_PATH\n\n\ Print\ the\ directories\ that\ were\ themselves\ changed\ (property\ edits)\n\ or\ whose\ file\ children\ were\ changed. help.description=usage:\ jsvnlook\ help\ [SUBCOMMAND...]\n\n\ Describe\ the\ usage\ of\ this\ program\ or\ its\ subcommands. history.description=usage:\ jsvnlook\ history\ REPOS_PATH\ [PATH_IN_REPOS]\n\n\ Print\ information\ about\ the\ history\ of\ a\ path\ in\ the\ repository\ (or\n\ the\ root\ directory\ if\ no\ path\ is\ supplied). info.description=usage:\ jsvnlook\ info\ REPOS_PATH\n\n\ Print\ the\ author,\ datestamp,\ log\ message\ size,\ and\ log\ message. lock.description=usage:\ jsvnlook\ lock\ REPOS_PATH\ PATH_IN_REPOS\n\n\ If\ a\ lock\ exists\ on\ a\ path\ in\ the\ repository,\ describe\ it. log.description=usage:\ jsvnlook\ log\ REPOS_PATH\n\n\ Print\ the\ log\ message. propget.description=usage:\ 1.\ jsvnlook\ propget\ REPOS_PATH\ PROPNAME\ PATH_IN_REPOS\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 2.\ jsvnlook\ propget\ --revprop\ REPOS_PATH\ PROPNAME\n\n\ Print\ the\ raw\ value\ of\ a\ property\ on\ a\ path\ in\ the\ repository.\n\ With\ --revprop,\ print\ the\ raw\ value\ of\ a\ revision\ property. proplist.description=usage:\ 1.\ jsvnlook\ proplist\ REPOS_PATH\ [PATH_IN_REPOS]\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 2.\ jsvnlook\ proplist\ --revprop\ REPOS_PATH\n\n\ List\ the\ properties\ of\ a\ path\ in\ the\ repository,\ or\n\ with\ the\ --revprop\ option,\ revision\ properties.\n\ With\ -v,\ show\ the\ property\ values\ too. tree.description=usage:\ jsvnlook\ tree\ REPOS_PATH\ [PATH_IN_REPOS]\n\n\ Print\ the\ tree,\ starting\ at\ PATH_IN_REPOS\ (if\ supplied,\ at\ the\ root\n\ of\ the\ tree\ otherwise),\ optionally\ showing\ node\ revision\ ids. youngest.description=usage:\ jsvnlook\ youngest\ REPOS_PATH\n\n\ Print\ the\ youngest\ revision\ number. uuid.description=usage:\ jsvnlook\ uuid\ REPOS_PATH\n\n\ Print\ the\ repository's\ UUID.svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnlook/options.properties000066400000000000000000000041521177510526000332550ustar00rootroot00000000000000copy-info=show\ details\ for\ copies diff-copy-from=print\ differences\ against\ the\ copy\ source full-paths=show\ full\ paths\ instead\ of\ indenting\ them help=show\ help\ on\ a\ subcommand limit=maximum\ number\ of\ history\ entries no-diff-added=do\ not\ print\ differences\ for\ added\ files no-diff-deleted=do\ not\ print\ differences\ for\ deleted\ files non-recursive=operate\ on\ single\ directory\ only revision=specify\ revision\ number\ ARG revprop=operate\ on\ a\ revision\ property\ (use\ with\ -r\ or\ -t) show-ids=show\ node\ revision\ ids\ for\ each\ path transaction=specify\ transaction\ name\ ARG verbose=be\ verbose xml=output\ in\ XML version=show\ program\ version\ information extensions=\ Default:\ '-u'.\ When\ Subversion\ is\ invoking\ an\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ external\ diff\ program,\ ARG\ is\ simply\ passed\ along\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ to\ the\ program.\ But\ when\ Subversion\ is\ using\ its\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ default\ internal\ diff\ implementation,\ or\ when\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Subversion\ is\ displaying\ blame\ annotations,\ ARG\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ could\ be\ any\ of\ the\ following:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -u\ (--unified):\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Output\ 3\ lines\ of\ unified\ context.\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -b\ (--ignore-space-change):\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Ignore\ changes\ in\ the\ amount\ of\ white\ space.\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -w\ (--ignore-all-space):\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Ignore\ all\ white\ space.\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ --ignore-eol-style:\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Ignore\ changes\ in\ EOL\ stylesvnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnsync/000077500000000000000000000000001177510526000274525ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnsync/commands.properties000066400000000000000000000037451177510526000334020ustar00rootroot00000000000000info.description=\ usage:\ jsvnsync\ info\ DEST_URL\n\ \n\ Print\ information\ about\ the\ synchronization\ destination\ repository\n\ located\ at\ DEST_URL. initialize.description=\ usage:\ jsvnsync\ initialize\ DEST_URL\ SOURCE_URL\n\ \n\ Initialize\ a\ destination\ repository\ for\ synchronization\ from\n\ another\ repository.\n\ \n\ The\ destination\ URL\ must\ point\ to\ the\ root\ of\ a\ repository\ with\n\ no\ committed\ revisions.\ \ The\ destination\ repository\ must\ allow\n\ revision\ property\ changes.\n\ \n\ If\ the\ source\ URL\ is\ not\ the\ root\ of\ a\ repository,\ only\ the\n\ specified\ part\ of\ the\ repository\ will\ be\ synchronized.\n\ \n\ You\ should\ not\ commit\ to,\ or\ make\ revision\ property\ changes\ in,\n\ the\ destination\ repository\ by\ any\ method\ other\ than\ 'jsvnsync'.\n\ In\ other\ words,\ the\ destination\ repository\ should\ be\ a\ read-only\n\ mirror\ of\ the\ source\ repository. synchronize.description=\ usage:\ jsvnsync\ synchronize\ DEST_URL\n\ \n\ Transfer\ all\ pending\ revisions\ to\ the\ destination\ from\ the\ source\n\ with\ which\ it\ was\ initialized. copy-revprops.description=\ usage:\ jsvnsync\ copy-revprops\ DEST_URL\ [REV[:REV2]]\n\ \n\ Copy\ the\ revision\ properties\ in\ a\ given\ range\ of\ revisions\ to\ the\n\ destination\ from\ the\ source\ with\ which\ it\ was\ initialized.\n\ \n\ If\ REV\ and\ REV2\ are\ provided,\ copy\ properties\ for\ the\ revisions\n\ specified\ by\ that\ range,\ inclusively.\ \ If\ only\ REV\ is\ provided,\n\ copy\ properties\ for\ that\ revision\ alone.\ \ If\ REV\ is\ not\ provided,\n\ copy\ properties\ for\ all\ revisions\ previously\ transferred\ to\ the\n\ destination.\n\ \n\ REV\ and\ REV2\ must\ be\ revisions\ which\ were\ previously\ transferred\n\ to\ the\ destination.\ \ You\ may\ use\ "HEAD"\ for\ either\ revision\ to\n\ mean\ "the\ last\ revision\ transferred". help.description=\ usage:\ jsvnsync\ help\ [SUBCOMMAND...]\n\ \n\ Describe\ the\ usage\ of\ this\ program\ or\ its\ subcommands.svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnsync/options.properties000066400000000000000000000020231177510526000332600ustar00rootroot00000000000000trust-server-cert=accept\ unknown\ SSL\ server\ certificates\ without\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ prompting\ (but\ only\ with\ '--non-interactive') quiet=print\ as\ little\ as\ possible non-interactive=do\ no\ interactive\ prompting no-auth-cache=do\ not\ cache\ authentication\ tokens username=specify\ a\ username\ ARG\ (deprecated;\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ see\ --source-username\ and\ --sync-username) password=specify\ a\ password\ ARG\ (deprecated;\n\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ see\ --source-password\ and\ --sync-password) source-username=connect\ to\ source\ repository\ with\ username\ ARG source-password=connect\ to\ source\ repository\ with\ password\ ARG sync-username=connect\ to\ sync\ repository\ with\ username\ ARG sync-password=connect\ to\ sync\ repository\ with\ password\ ARG config-dir=read\ user\ configuration\ files\ from\ directory\ ARG version=show\ program\ version\ information help=show\ help\ on\ a\ subcommandsvnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnversion/000077500000000000000000000000001177510526000301635ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnversion/commands.properties000066400000000000000000000025631177510526000341100ustar00rootroot00000000000000.description=\ usage:\ jsvnversion\ [OPTIONS]\ [WC_PATH\ [TRAIL_URL]]\n\n\ \ \ Produce\ a\ compact\ 'version\ number'\ for\ the\ working\ copy\ path\n\ \ \ WC_PATH.\ \ TRAIL_URL\ is\ the\ trailing\ portion\ of\ the\ URL\ used\ to\n\ \ \ determine\ if\ WC_PATH\ itself\ is\ switched\ (detection\ of\ switches\n\ \ \ within\ WC_PATH\ does\ not\ rely\ on\ TRAIL_URL).\ \ The\ version\ number\n\ \ \ is\ written\ to\ standard\ output.\ \ For\ example:\n\ \n\ \ \ \ \ $\ jsvnversion\ .\ /repos/svn/trunk\n\ \ \ \ \ 4168\n\ \n\ \ \ The\ version\ number\ will\ be\ a\ single\ number\ if\ the\ working\n\ \ \ copy\ is\ single\ revision,\ unmodified,\ not\ switched\ and\ with\n\ \ \ an\ URL\ that\ matches\ the\ TRAIL_URL\ argument.\ \ If\ the\ working\n\ \ \ copy\ is\ unusual\ the\ version\ number\ will\ be\ more\ complex:\n\ \n\ \ \ \ 4123:4168\ \ \ \ \ mixed\ revision\ working\ copy\n\ \ \ \ 4168M\ \ \ \ \ \ \ \ \ modified\ working\ copy\n\ \ \ \ 4123S\ \ \ \ \ \ \ \ \ switched\ working\ copy\n\ \ \ \ 4123P\ \ \ \ \ \ \ \ \ partial\ working\ copy,\ from\ a\ sparse\ checkout\n\ \ \ \ 4123:4168MS\ \ \ mixed\ revision,\ modified,\ switched\ working\ copy\n\ \n\ \ \ If\ invoked\ on\ a\ directory\ that\ is\ not\ a\ working\ copy,\ an\n\ \ \ exported\ directory\ say,\ the\ program\ will\ output\ 'exported'.\n\ \n\ \ \ If\ invoked\ without\ arguments\ WC_PATH\ will\ be\ the\ current\ directory.svnkit-1.7.5+dfsg/svnkit-cli/src/main/resources/org/tmatesoft/svn/cli/svnversion/options.properties000066400000000000000000000002611177510526000337730ustar00rootroot00000000000000no-newline=do\ not\ output\ the\ trailing\ newline committed=last\ changed\ rather\ than\ current\ revisions help=display\ this\ help version=show\ program\ version\ informationsvnkit-1.7.5+dfsg/svnkit-cli/src/main/scripts/000077500000000000000000000000001177510526000212525ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-cli/src/main/scripts/jsvn000066400000000000000000000043731177510526000221640ustar00rootroot00000000000000BASEDIR=`dirname $0`/.. BASEDIR=`(cd "$BASEDIR"; pwd)` cygwin=false; darwin=false; case "`uname`" in CYGWIN*) cygwin=true ;; Darwin*) darwin=true if [ -z "$JAVA_VERSION" ] ; then JAVA_VERSION="CurrentJDK" else echo "Using Java version: $JAVA_VERSION" fi if [ -z "$JAVA_HOME" ] ; then JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Home fi ;; esac if [ -z "$JAVA_HOME" ] ; then if [ -r /etc/gentoo-release ] ; then JAVA_HOME=`java-config --jre-home` fi fi # For Cygwin, ensure paths are in UNIX format before anything is touched if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` [ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --unix "$CLASSPATH"` fi # If a specific java binary isn't specified search for the standard 'java' binary if [ -z "$JAVACMD" ] ; then if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi else JAVACMD=`which java` fi fi if [ ! -x "$JAVACMD" ] ; then echo "Error: JAVA_HOME is not defined correctly." echo " We cannot execute $JAVACMD" exit 1 fi if [ -z "$SVNKIT_LIB" ] then SVNKIT_LIB="$BASEDIR"/lib fi CLASSPATH="$BASEDIR/conf" CLASSPATH=$CLASSPATH:"$SVNKIT_LIB/${classpathEntry}" LOGGING_PROPERTIES_PATH="$BASEDIR/conf/logging.properties" # For Cygwin, switch paths to Windows format before running java if $cygwin; then [ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --windows "$CLASSPATH"` [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` [ -n "$HOME" ] && HOME=`cygpath --path --windows "$HOME"` [ -n "$BASEDIR" ] && BASEDIR=`cygpath --path --windows "$BASEDIR"` [ -n "$REPO" ] && REPO=`cygpath --path --windows "$REPO"` [ -n "$LOGGING_PROPERTIES_PATH" ] && REPO=`cygpath --path --windows "$LOGGING_PROPERTIES_PATH"` fi EXTRA_JVM_ARGUMENTS="-Djava.util.logging.config.file=$LOGGING_PROPERTIES_PATH -Dsun.io.useCanonCaches=false" exec "$JAVACMD" $JAVA_OPTS \ $EXTRA_JVM_ARGUMENTS \ -classpath "$CLASSPATH" \ @mainclass@ \ "$@" svnkit-1.7.5+dfsg/svnkit-cli/src/main/scripts/jsvn.bat000066400000000000000000000037701177510526000227310ustar00rootroot00000000000000@echo off set ERROR_CODE=0 :init @REM Decide how to startup depending on the version of windows @REM -- Win98ME if NOT "%OS%"=="Windows_NT" goto Win9xArg @REM set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" @setlocal @REM -- 4NT shell if "%eval[2+2]" == "4" goto 4NTArgs @REM -- Regular WinNT shell set CMD_LINE_ARGS=%* goto WinNTGetScriptDir @REM The 4NT Shell from jp software :4NTArgs set CMD_LINE_ARGS=%$ goto WinNTGetScriptDir :Win9xArg @REM Slurp the command line arguments. This loop allows for an unlimited number @REM of arguments (up to the command line limit, anyway). set CMD_LINE_ARGS= :Win9xApp if %1a==a goto Win9xGetScriptDir set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1 shift goto Win9xApp :Win9xGetScriptDir set SAVEDIR=%CD% %0\ cd %0\..\.. set BASEDIR=%CD% cd %SAVEDIR% set SAVE_DIR= goto repoSetup :WinNTGetScriptDir set BASEDIR=%~dp0 IF %BASEDIR:~-1%==\ SET BASEDIR=%BASEDIR:~0,-1% set BASEDIR=%BASEDIR%\.. :repoSetup if "%JAVACMD%"=="" set JAVACMD=java if not "%JAVA_HOME%"=="" set JAVACMD="%JAVA_HOME%\bin\%JAVACMD%" if "%SVNKIT_LIB%"=="" set SVNKIT_LIB=%BASEDIR%\lib set CLASSPATH= set CLASSPATH=%CLASSPATH%;"%SVNKIT_LIB%\${classpathEntry}" set EXTRA_JVM_ARGUMENTS=-Djava.util.logging.config.file="%BASEDIR%\conf\logging.properties" -Dsun.io.useCanonCaches=false goto endInit @REM Reaching here means variables are defined and arguments have been captured :endInit %JAVACMD% %JAVA_OPTS% %EXTRA_JVM_ARGUMENTS% -classpath %CLASSPATH% @mainclass@ %CMD_LINE_ARGS% if ERRORLEVEL 1 goto error goto end :error if "%OS%"=="Windows_NT" @endlocal set ERROR_CODE=1 :end @REM set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" goto endNT @REM For old DOS remove the set variables from ENV - we assume they were not set @REM before we started - at least we don't leave any baggage around set CMD_LINE_ARGS= goto postExec :endNT @endlocal :postExec if "%FORCE_EXIT_ON_ERROR%" == "on" ( if %ERROR_CODE% NEQ 0 exit %ERROR_CODE% ) exit /B %ERROR_CODE% svnkit-1.7.5+dfsg/svnkit-cli/src/main/scripts/jsvnsetup.openvms000066400000000000000000000026031177510526000247250ustar00rootroot00000000000000$! $ if f$type(java) .nes. "STRING" .or. "''java'" .eqs. "" $ then $ write SYS$OUTPUT "You must have the JAVA symbol properly set before using this command" $ exit $ endif $ env = f$env("PROCEDURE") $ home = f$parse(env,,,"device") + f$parse(env,,,"directory") $ define/job/nolog svnkit_home 'home' $! $ define/job/nolog decc$argv_parse_style enable $ define/job/nolog decc$efs_case_preserve enable $! $ if f$edit(f$trnlnm("DECC$EFS_CASE_SPECIAL"),"UPCASE") .eqs. "ENABLE" $ then $ write sys$output " " $ write sys$output "JSVNSETUP: DECC$EFS_CASE_SPECIAL defined! Please deassign logical otherwise jsvn might not function properly!" $ write sys$output " " $ endif $! $! $ CP = "/svnkit_home/../lib" $ CP = CP + ":/svnkit_home/../lib/${classpathEntry} $ OPT = "" $! OPT = "-Djava.util.logging.config.file=/svnkit_home/../conf/logging.properties" $! $ JV = f$edit(java,"collapse") $ jsvn == "''JV' ''OPT' -cp ''CP' ""org.tmatesoft.svn.cli.svn.SVN""" $ jsvnadmin == "''JV' ''OPT' -cp ''CP' ""org.tmatesoft.svn.cli.svnadmin.SVNAdmin""" $ jsvnlook == "''JV' ''OPT' -cp ''CP' ""org.tmatesoft.svn.cli.svnlook.SVNLook""" $ jsvnsync == "''JV' ''OPT' -cp ''CP' ""org.tmatesoft.svn.cli.svnsync.SVNSync""" $ jsvndumpfilter == "''JV' ''OPT' -cp ''CP' ""org.tmatesoft.svn.cli.svndumpfilter.SVNDumpFilter""" $ jsvnversion == "''JV' ''OPT' -cp ''CP' ""org.tmatesoft.svn.cli.svnversion.SVNVersion""" $! svnkit-1.7.5+dfsg/svnkit-dav/000077500000000000000000000000001177510526000160535ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/000077500000000000000000000000001177510526000166425ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/000077500000000000000000000000001177510526000175665ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/000077500000000000000000000000001177510526000205075ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/000077500000000000000000000000001177510526000212765ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/000077500000000000000000000000001177510526000233045ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/000077500000000000000000000000001177510526000241125ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/000077500000000000000000000000001177510526000250425ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/000077500000000000000000000000001177510526000266565ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/000077500000000000000000000000001177510526000301645ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/000077500000000000000000000000001177510526000307365ustar00rootroot00000000000000DAVActivityResourceHelper.java000066400000000000000000000022531177510526000365230ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVActivityResourceHelper extends DAVResourceHelper { protected void prepare(DAVResource resource) throws DAVException { String txnName = DAVServletUtil.getTxn(resource.getActivitiesDB(), resource.getResourceURI().getActivityID()); resource.setTxnName(txnName); resource.setExists(txnName != null); } protected DAVResource getParentResource(DAVResource resource) throws DAVException { return DAVPrivateResourceHelper.createPrivateResource(resource, DAVResourceKind.ACT_COLLECTION); } } DAVAutoVersion.java000066400000000000000000000016131177510526000343340ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVAutoVersion { public static DAVAutoVersion NEVER = new DAVAutoVersion(); public static DAVAutoVersion ALWAYS = new DAVAutoVersion(); public static DAVAutoVersion LOCKED = new DAVAutoVersion(); private DAVAutoVersion() { } } svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/DAVConfig.java000066400000000000000000000152301177510526000333420ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.File; import javax.servlet.ServletConfig; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVConfig { private static final String PATH_DIRECIVE = "SVNPath"; private static final String PARENT_PATH_DIRECIVE = "SVNParentPath"; private static final String SVN_ACCESS_FILE_DIRECTIVE = "AuthzSVNAccessFile"; private static final String SVN_ANONYMOUS_DIRECTIVE = "AuthzSVNAnonymous"; private static final String SVN_NO_AUTH_IF_ANONYMOUS_ALLOWED_DIRECIVE = "AuthzSVNNoAuthWhenAnonymousAllowed"; private static final String LIST_PARENT_PATH_DIRECTIVE = "SVNListParentPath"; private static final String REPOS_NAME = "SVNReposName"; private static final String XSLT_INDEX = "SVNIndexXSLT"; private static final String ACTIVITIES_DB = "SVNActivitiesDB"; private static final String AUTOVERSIONING = "SVNAutoversioning"; private static final String ALLOW_BULK_UPDATES = "SVNAllowBulkUpdates"; private static final String DAV_DEPTH = "DAVDepthInfinity"; private static final String OFF = "off"; private static final String ON = "on"; private String myRepositoryPath; private String myRepositoryParentPath; private String myRepositoryName; private String myXSLTIndex; private String myActivitiesDBPath; private SVNPathBasedAccess mySVNAccess = null; private boolean myUsingPBA = false; private boolean myAnonymous = true; private boolean myNoAuthIfAnonymousAllowed = false; private boolean myIsListParentPath = false; private boolean myIsAutoVersioning = false; private boolean myIsAllowBulkUpdates = false; private boolean myIsAllowDepthInfinity = false; public DAVConfig(ServletConfig servletConfig) throws SVNException { String repositoryPath = servletConfig.getInitParameter(PATH_DIRECIVE); String repositoryParentPath = servletConfig.getInitParameter(PARENT_PATH_DIRECIVE); myRepositoryName = servletConfig.getInitParameter(REPOS_NAME); myXSLTIndex = servletConfig.getInitParameter(XSLT_INDEX); if (repositoryPath != null && repositoryParentPath == null) { myRepositoryPath = repositoryPath; myRepositoryParentPath = null; } else if (repositoryParentPath != null && repositoryPath == null) { myRepositoryParentPath = repositoryParentPath; myRepositoryPath = null; } else { //repositoryPath == null <=> repositoryParentPath == null. if (repositoryPath == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "Neither SVNPath nor SVNParentPath directive were specified."), SVNLogType.NETWORK); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "Only one of SVNPath and SVNParentPath directives should be specified."), SVNLogType.NETWORK); } } String configurationFilePath = servletConfig.getInitParameter(SVN_ACCESS_FILE_DIRECTIVE); if (configurationFilePath != null) { myUsingPBA = true; try { mySVNAccess = new SVNPathBasedAccess(new File(configurationFilePath)); } catch (SVNException e) { mySVNAccess = null; } } String anonymous = servletConfig.getInitParameter(SVN_ANONYMOUS_DIRECTIVE); if (anonymous != null && OFF.equals(anonymous)) { myAnonymous = false; } String noAuthIfAnonymousAllowed = servletConfig.getInitParameter(SVN_NO_AUTH_IF_ANONYMOUS_ALLOWED_DIRECIVE); if (noAuthIfAnonymousAllowed != null && ON.equals(noAuthIfAnonymousAllowed)) { myNoAuthIfAnonymousAllowed = true; } String listParentPath = servletConfig.getInitParameter(LIST_PARENT_PATH_DIRECTIVE); if (listParentPath != null && ON.equals(listParentPath)) { myIsListParentPath = true; } String autoversioning = servletConfig.getInitParameter(AUTOVERSIONING); if (autoversioning != null && ON.equals(autoversioning)) { myIsAutoVersioning = true; } String allowBulkUpdates = servletConfig.getInitParameter(ALLOW_BULK_UPDATES); if (allowBulkUpdates != null && ON.equals(allowBulkUpdates)) { myIsAllowBulkUpdates = true; } String allowDepthInfinity = servletConfig.getInitParameter(DAV_DEPTH); if (allowDepthInfinity != null && ON.equals(allowDepthInfinity)) { myIsAllowDepthInfinity = true; } myActivitiesDBPath = servletConfig.getInitParameter(ACTIVITIES_DB); } public boolean isAllowDepthInfinity() { return myIsAllowDepthInfinity; } public String getRepositoryName() { return myRepositoryName; } public String getXSLTIndex() { return myXSLTIndex; } public boolean isUsingRepositoryPathDirective() { return myRepositoryPath != null; } public String getRepositoryPath() { return myRepositoryPath; } public String getRepositoryParentPath() { return myRepositoryParentPath; } public SVNPathBasedAccess getSVNAccess() { return mySVNAccess; } public boolean isUsingPBA() { return myUsingPBA; } public boolean isAnonymousAllowed() { return myAnonymous; } public boolean isNoAuthIfAnonymousAllowed() { return myNoAuthIfAnonymousAllowed; } public boolean isListParentPath() { return myIsListParentPath; } public String getActivitiesDBPath() { return myActivitiesDBPath; } public boolean isAutoVersioning() { return myIsAutoVersioning; } public boolean isAllowBulkUpdates() { return myIsAllowBulkUpdates; } } svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/DAVDepth.java000066400000000000000000000043351177510526000332050ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVDepth { public static final DAVDepth DEPTH_ZERO = new DAVDepth(0, "0"); public static final DAVDepth DEPTH_ONE = new DAVDepth(1, "1"); public static final DAVDepth DEPTH_INFINITY = new DAVDepth(Integer.MAX_VALUE, "infinity"); private int myID; private String myName; private DAVDepth(int id, String name) { myID = id; myName = name; } public int getID() { return myID; } public String toString() { return myName; } public static DAVDepth parseDepth(String depth) { if (DAVDepth.DEPTH_INFINITY.toString().equalsIgnoreCase(depth)) { return DAVDepth.DEPTH_INFINITY; } else if (DAVDepth.DEPTH_ZERO.toString().equalsIgnoreCase(depth)) { return DAVDepth.DEPTH_ZERO; } else if (DAVDepth.DEPTH_ONE.toString().equalsIgnoreCase(depth)) { return DAVDepth.DEPTH_ONE; } return null; } public static DAVDepth decreaseDepth(DAVDepth currentDepth) throws SVNException { if (currentDepth == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, "Depth is not specified."), SVNLogType.NETWORK); } if (currentDepth == DEPTH_ZERO || currentDepth == DEPTH_INFINITY) { return currentDepth; } return DAVDepth.DEPTH_ZERO; } } DAVErrorCode.java000066400000000000000000000030771177510526000337500ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVErrorCode { public static final int IF_PARSE = 100; public static final int IF_MULTIPLE_NOT = 101; public static final int IF_UNK_CHAR = 102; public static final int IF_ABSENT = 103; public static final int IF_TAGGED = 104; public static final int IF_UNCLOSED_PAREN = 105; public static final int PROP_BAD_MAJOR = 200; public static final int PROP_READONLY = 201; public static final int PROP_NO_DATABASE = 202; public static final int PROP_NOT_FOUND = 203; public static final int PROP_BAD_LOCKDB = 204; public static final int PROP_OPENING = 205; public static final int PROP_EXEC = 206; public static final int LOCK_OPENDB = 400; public static final int LOCK_NODB = 401; public static final int CORRUPT_DB = 402; public static final int UNK_STATE_TOKEN = 403; public static final int PARSE_TOKEN = 404; public static final int LOCK_SAVE_LOCK = 405; } DAVException.java000066400000000000000000000143641177510526000340230ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.text.MessageFormat; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.handlers.DAVResponse; import org.tmatesoft.svn.core.internal.server.dav.handlers.ServletDAVHandler; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.1.2 * @author TMate Software Ltd. */ public class DAVException extends SVNException { private static final long serialVersionUID = 4845L; private String myMessage; private int myResponseCode; private int myErrorID; private DAVException myPreviousException; private String myTagName; private String myNameSpace; private DAVResponse myResponse; public DAVException(String message, Object[] objects, int responseCode, SVNErrorMessage error, SVNLogType logType, Level level, DAVException previousException, String tagName, String nameSpace, int errorID, DAVResponse response) { super(error != null ? error : SVNErrorMessage.create(SVNErrorCode.UNKNOWN)); myMessage = objects == null ? message : MessageFormat.format(message, objects); myResponseCode = responseCode; myPreviousException = previousException; myTagName = tagName; myNameSpace = nameSpace; myErrorID = errorID; myResponse = response; SVNDebugLog.getDefaultLog().log(logType, message, level); } public DAVException(String message, int respondCode, DAVException previousException, int errorID) { this(message, null, respondCode, null, SVNLogType.NETWORK, Level.FINE, previousException, null, null, errorID, null); } public DAVException(String message, Object[] objects, int respondCode, DAVException previousException, int errorID) { this(message, objects, respondCode, null, SVNLogType.NETWORK, Level.FINE, previousException, null, null, errorID, null); } public DAVException(String message, int responseCode, SVNLogType logType) { this(message, null, responseCode, null, logType, Level.FINE, null, null, null, 0, null); } public DAVException(String message, int responseCode, SVNLogType logType, DAVResponse response) { this(message, null, responseCode, null, logType, Level.FINE, null, null, null, 0, response); } public DAVException(String message, int responseCode, SVNLogType logType, String tagName, String nameSpace) { this(message, null, responseCode, null, logType, Level.FINE, null, tagName, nameSpace, 0, null); } public DAVException(String message, Object[] objects, int responseCode, int errorID) { this(message, objects, responseCode, null, SVNLogType.NETWORK, Level.FINE, null, null, null, errorID, null); } public DAVException(String message, Object[] objects, int responseCode, int errorID, DAVResponse response) { this(message, objects, responseCode, null, SVNLogType.NETWORK, Level.FINE, null, null, null, errorID, response); } public DAVException(String message, int responseCode, int errorID) { this(message, null, responseCode, errorID); } public DAVException(String message, int responseCode, int errorID, DAVResponse response) { this(message, null, responseCode, errorID, response); } public int getErrorID() { return myErrorID; } public String getTagName() { return myTagName; } public int getResponseCode() { return myResponseCode; } public String getMessage() { return myMessage; } public DAVException getPreviousException() { return myPreviousException; } public String getNameSpace() { return myNameSpace; } public DAVResponse getResponse() { return myResponse; } public void setResponse(DAVResponse response) { myResponse = response; } public void setPreviousException(DAVException previousException) { myPreviousException = previousException; } public static DAVException convertError(SVNErrorMessage err, int statusCode, String message, Object[] objects) { if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND) { statusCode = HttpServletResponse.SC_NOT_FOUND; } else if (err.getErrorCode() == SVNErrorCode.UNSUPPORTED_FEATURE) { statusCode = HttpServletResponse.SC_NOT_IMPLEMENTED; } else if (err.getErrorCode() == SVNErrorCode.FS_PATH_ALREADY_LOCKED) { statusCode = ServletDAVHandler.SC_HTTP_LOCKED; } DAVException error = buildErrorChain(err, statusCode); if (message != null && err.getErrorCode() != SVNErrorCode.REPOS_HOOK_FAILURE) { if (objects != null) { message = MessageFormat.format(message, objects); } error = new DAVException(message, null, statusCode, null, SVNLogType.NETWORK, Level.FINE, error, null, null, err.getErrorCode().getCode(), null); } return error; } private static DAVException buildErrorChain(SVNErrorMessage err, int statusCode) { DAVException error = new DAVException(err.getMessage(), null, statusCode, err, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, err.getErrorCode().getCode(), null); if (err.getChildErrorMessage() != null) { error.setPreviousException(buildErrorChain(err.getChildErrorMessage(), statusCode)); } return error; } } DAVHistoryResourceHelper.java000066400000000000000000000017151177510526000363720ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVHistoryResourceHelper extends DAVResourceHelper { protected void prepare(DAVResource resource) throws DAVException { } public DAVResource getParentResource(DAVResource resource) throws DAVException { DAVResourceHelper.throwIllegalGetParentResourceError(resource); return null; } } DAVIFHeader.java000066400000000000000000000024721177510526000334710ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.util.LinkedList; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVIFHeader { private String myURI; private LinkedList myStateList; private boolean myIsDummyHeader; public DAVIFHeader(String uri) { this(uri, false); } public DAVIFHeader(String uri, boolean isDummy) { myURI = uri; myStateList = new LinkedList(); myIsDummyHeader = isDummy; } public void addIFState(DAVIFState ifState) { myStateList.addFirst(ifState); } public boolean isDummyHeader() { return myIsDummyHeader; } public String getURI() { return myURI; } public LinkedList getStateList() { return myStateList; } } DAVIFState.java000066400000000000000000000025631177510526000333620ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVIFState { public static final int IF_CONDITION_NORMAL = 0; public static final int IF_CONDITION_NOT = 1; private DAVIFStateType myType; private String myETag; private String myLockToken; private int myCondition; public DAVIFState(int condition, String tag, String lockToken, DAVIFStateType type) { myCondition = condition; myETag = tag; myType = type; myLockToken = lockToken; } public DAVIFStateType getType() { return myType; } public String getLockToken() { return myLockToken; } public String getETag() { return myETag; } public int getCondition() { return myCondition; } } DAVIFStateType.java000066400000000000000000000016461177510526000342250ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVIFStateType { public static final DAVIFStateType IF_ETAG = new DAVIFStateType(); public static final DAVIFStateType IF_OPAQUE_LOCK = new DAVIFStateType(); public static final DAVIFStateType IF_UNKNOWN = new DAVIFStateType(); private DAVIFStateType() { } } svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/DAVLock.java000066400000000000000000000040401177510526000330220ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.util.Date; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVLock { private DAVLockRecType myRecType; private DAVLockScope myScope; private DAVLockType myType; private boolean myIsLockNull; private DAVDepth myDepth; private String myLockToken; private String myOwner; private String myAuthUser; private Date myTimeOutDate; public DAVLock(String authUser, DAVDepth depth, boolean isLockNull, String lockToken, String owner, DAVLockRecType recType, DAVLockScope scope, DAVLockType type, Date timeOutDate) { myAuthUser = authUser; myDepth = depth; myIsLockNull = isLockNull; myLockToken = lockToken; myOwner = owner; myRecType = recType; myScope = scope; myType = type; myTimeOutDate = timeOutDate; } public DAVLockRecType getRecType() { return myRecType; } public DAVLockScope getScope() { return myScope; } public DAVLockType getType() { return myType; } public boolean isLockNull() { return myIsLockNull; } public DAVDepth getDepth() { return myDepth; } public String getLockToken() { return myLockToken; } public String getOwner() { return myOwner; } public String getAuthUser() { return myAuthUser; } public Date getTimeOutDate() { return myTimeOutDate; } } DAVLockRecType.java000066400000000000000000000016511177510526000342440ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVLockRecType { public static final DAVLockRecType DIRECT = new DAVLockRecType(); public static final DAVLockRecType INDIRECT = new DAVLockRecType(); public static final DAVLockRecType INDIRECT_PARTIAL = new DAVLockRecType(); private DAVLockRecType() { } } DAVLockScope.java000066400000000000000000000016211177510526000337370ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVLockScope { public static final DAVLockScope EXCLUSIVE = new DAVLockScope(); public static final DAVLockScope UNKNOWN = new DAVLockScope(); public static final DAVLockScope SHARED = new DAVLockScope(); private DAVLockScope() { } } DAVLockType.java000066400000000000000000000015051177510526000336100ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVLockType { public static final DAVLockType UNKNOWN = new DAVLockType(); public static final DAVLockType WRITE = new DAVLockType(); private DAVLockType() { } } DAVPathUtil.java000066400000000000000000000242761177510526000336220ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVPathUtil { private static final String SLASH = "/"; public static String dropLeadingSlash(String uri) { if (uri == null) { return ""; } return uri.startsWith(SLASH) ? uri.substring(SLASH.length()) : uri; } public static String addLeadingSlash(String uri) { if (uri == null) { return SLASH; } return uri.startsWith(SLASH) ? uri : SLASH + uri; } public static String dropTraillingSlash(String uri) { if (uri == null) { return ""; } return uri.endsWith(SLASH) ? uri.substring(0, uri.length() - SLASH.length()) : uri; } public static String addTrailingSlash(String uri) { if (uri == null) { return SLASH; } return uri.endsWith(SLASH) ? uri : uri + SLASH; } public static String head(String uri) { uri = dropLeadingSlash(uri); int slashIndex = uri.indexOf(SLASH); if (slashIndex == -1) { return uri; } return uri.substring(0, slashIndex); } public static String removeHead(String uri, boolean doStandardize) { uri = dropLeadingSlash(uri); int headLength = head(uri).length(); return doStandardize ? standardize(uri.substring(headLength)) : uri.substring(headLength); } public static String tail(String uri) { uri = dropTraillingSlash(uri); int lastSlashIndex = uri.lastIndexOf(SLASH); if (lastSlashIndex == -1) { return uri; } return uri.substring(lastSlashIndex); } public static String removeTail(String uri, boolean doStandardize) { uri = dropTraillingSlash(uri); int tailLength = tail(uri).length(); return doStandardize ? standardize(uri.substring(0, uri.length() - tailLength)) : uri.substring(0, uri.length() - tailLength); } public static String append(String parent, String child) { StringBuffer uriBuffer = new StringBuffer(); uriBuffer.append(standardize(parent)); uriBuffer.append(standardize(child)); return uriBuffer.toString(); } public static String standardize(String uri) { if (uri == null) { return SLASH; } return addLeadingSlash(dropTraillingSlash(uri)); } public static String normalize(String uri) { return "".equals(uri) ? SLASH : uri; } public static void testCanonical(String path) throws DAVException { if (path != null && !path.equals(SVNPathUtil.canonicalizePath(path))) { throw new DAVException("Path ''{0}'' is not canonicalized;\nthere is a problem with the client.", new Object[] { path }, HttpServletResponse.SC_BAD_REQUEST, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, 0, null); } } public static String buildURI(String context, DAVResourceKind davResourceKind, long revision, String path, boolean addHref) { StringBuffer resultURI = new StringBuffer(); path = path == null ? "" : SVNEncodingUtil.uriEncode(path); context = context == null ? "" : context; if (addHref) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, resultURI); } resultURI.append(context); resultURI.append(SLASH); if (davResourceKind == DAVResourceKind.PUBLIC) { resultURI.append(dropLeadingSlash(path)); } else { resultURI.append(DAVResourceURI.SPECIAL_URI).append(SLASH); if (davResourceKind == DAVResourceKind.ACT_COLLECTION) { resultURI.append(davResourceKind.toString()); resultURI.append(SLASH); } else if (davResourceKind == DAVResourceKind.BASELINE) { resultURI.append(davResourceKind.toString()); resultURI.append(SLASH); resultURI.append(String.valueOf(revision)); } else if (davResourceKind == DAVResourceKind.BASELINE_COLL) { resultURI.append(davResourceKind.toString()); resultURI.append(SLASH); resultURI.append(String.valueOf(revision)); resultURI.append(addLeadingSlash(path)); } else if (davResourceKind == DAVResourceKind.VERSION) { resultURI.append(davResourceKind.toString()); resultURI.append(SLASH); resultURI.append(String.valueOf(revision)); resultURI.append(addLeadingSlash(path)); } else if (davResourceKind == DAVResourceKind.VCC) { resultURI.append(davResourceKind.toString()); resultURI.append(SLASH); resultURI.append(DAVResourceURI.DEDAULT_VCC_NAME); } } if (addHref) { SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), resultURI, false); } return resultURI.toString(); } public static File getActivityPath(File activitiesDB, String activityID) { String safeActivityID = SVNFileUtil.computeChecksum(activityID); File finalActivityFile = new File(activitiesDB, safeActivityID); return finalActivityFile; } public static DAVURIInfo simpleParseURI(String uri, DAVResource relative) throws SVNException { URI parsedURI = null; try { parsedURI = new URI(uri); } catch (URISyntaxException urise) { throwMalformedURIErrorException(); } String path = parsedURI.getPath(); if ("".equals(path)) { path = "/"; } String reposRoot = relative.getResourceURI().getContext(); if (!path.equals(reposRoot) && (!path.startsWith(reposRoot) || path.charAt(reposRoot.length()) != '/')) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.APMOD_MALFORMED_URI, "Unusable URI: it does not refer to this repository"); SVNErrorManager.error(err, SVNLogType.NETWORK); } long revision = SVNRepository.INVALID_REVISION; path = path.substring(reposRoot.length()); if ("".equals(path) || "/".equals(path)) { return new DAVURIInfo(null, "/", revision); } path = path.substring(1); String specialURI = DAVResourceURI.SPECIAL_URI; if (!path.equals(specialURI) && (!path.startsWith(specialURI) || path.charAt(specialURI.length()) != '/')) { path = !path.startsWith("/") ? "/" + path : path; return new DAVURIInfo(null, path, revision); } path = path.substring(specialURI.length()); if ("".equals(path) || "/".equals(path)) { throwUnhandledFormException(); } int slashInd = path.indexOf('/', 1); if (slashInd == -1 || slashInd == path.length() -1) { throwUnhandledFormException(); } String segment = path.substring(0, slashInd + 1); String activityID = null; String reposPath = null; if ("/act/".equals(segment)) { activityID = path.substring(slashInd + 1); } else if ("/ver/".equals(segment)) { int nextSlashInd = path.indexOf('/', slashInd + 1); if (nextSlashInd == -1) { try { revision = Long.parseLong(path.substring(slashInd + 1)); } catch (NumberFormatException nfe) { throwMalformedURIErrorException(); } reposPath = "/"; } else { segment = path.substring(slashInd + 1, nextSlashInd); try { revision = Long.parseLong(segment); } catch (NumberFormatException nfe) { throwMalformedURIErrorException(); } reposPath = SVNEncodingUtil.uriDecode(path.substring(nextSlashInd)); } if (!SVNRevision.isValidRevisionNumber(revision)) { throwMalformedURIErrorException(); } } else { throwUnhandledFormException(); } return new DAVURIInfo(activityID, reposPath, revision); } private static void throwMalformedURIErrorException() throws SVNException { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.APMOD_MALFORMED_URI, "The specified URI could not be parsed"); SVNErrorManager.error(err, SVNLogType.NETWORK); } private static void throwUnhandledFormException() throws SVNException { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Unsupported URI form"); SVNErrorManager.error(err, SVNLogType.NETWORK); } } DAVPrivateResourceHelper.java000066400000000000000000000033511177510526000363410ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import org.tmatesoft.svn.core.io.SVNRepository; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVPrivateResourceHelper extends DAVResourceHelper { protected void prepare(DAVResource resource) throws DAVException { } protected DAVResource getParentResource(DAVResource resource) throws DAVException { DAVResourceHelper.throwIllegalGetParentResourceError(resource); return null; } public static DAVResource createPrivateResource(DAVResource resource, DAVResourceKind resourceKind) { DAVResource privateResource = new DAVResource(); resource.copyTo(privateResource); DAVResourceURI resourceURI = privateResource.getResourceURI(); resourceURI.setKind(resourceKind); resourceURI.setType(DAVResourceType.PRIVATE); String path = "/" + DAVResourceURI.SPECIAL_URI + "/" + resourceKind.toString(); resourceURI.setURI(path); resourceURI.setPath(null); privateResource.setCollection(true); privateResource.setExists(true); privateResource.setRevision(SVNRepository.INVALID_REVISION); return privateResource; } } DAVRegularResourceHelper.java000066400000000000000000000063011177510526000363260ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVRegularResourceHelper extends DAVResourceHelper { protected void prepare(DAVResource resource) throws DAVException { if (!SVNRevision.isValidRevisionNumber(resource.getRevision())) { try { resource.setRevision(resource.getLatestRevision()); } catch (SVNException e) { throw DAVException.convertError(e.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not determine the proper revision to access", null); } } FSRoot root = resource.getRoot(); FSFS fsfs = resource.getFSFS(); if (root == null) { try { root = fsfs.createRevisionRoot(resource.getRevision()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open the root of the repository", null); } resource.setRoot(root); } SVNNodeKind kind = DAVServletUtil.checkPath(root, resource.getResourceURI().getPath()); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "resource path is " + resource.getResourceURI().getPath()); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "resource kind is " + kind); resource.setExists(kind != SVNNodeKind.NONE); resource.setCollection(kind == SVNNodeKind.DIR); } protected DAVResource getParentResource(DAVResource resource) throws DAVException { DAVResource parentResource = new DAVResource(); resource.copyTo(parentResource); DAVResourceURI parentResourceURI = parentResource.getResourceURI(); String uri = parentResourceURI.getURI(); String path = parentResourceURI.getPath(); parentResourceURI.setURI(SVNPathUtil.removeTail(uri)); parentResourceURI.setPath(SVNPathUtil.removeTail(path)); parentResource.setExists(true); parentResource.setCollection(true); parentResource.setVersioned(true); return parentResource; } } DAVRepositoryManager.java000066400000000000000000000337771177510526000355500ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.File; import java.security.Principal; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.BasicAuthenticationManager; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication; import org.tmatesoft.svn.core.internal.server.dav.handlers.DAVHandlerFactory; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVRepositoryManager { private static final String FILE_PROTOCOL_LINE = "file://"; private static final String DESTINATION_HEADER = "Destination"; private static final String DEFAULT_ACTIVITY_DB = "dav/activities.d"; private DAVConfig myDAVConfig; private String myResourceRepositoryRoot; private String myResourceContext; private String myResourcePathInfo; private Principal myUserPrincipal; private File myRepositoryRootDir; public DAVRepositoryManager(DAVConfig config, HttpServletRequest request) throws SVNException { if (config == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE), SVNLogType.NETWORK); } myDAVConfig = config; myResourceRepositoryRoot = getRepositoryRoot(request.getPathInfo()); myResourceContext = getResourceContext(request); myUserPrincipal = request.getUserPrincipal(); myRepositoryRootDir = getRepositoryRootDir(request.getPathInfo()); myResourcePathInfo = getResourcePathInfo(request); if (config.isUsingPBA()) { String path = null; if (!DAVHandlerFactory.METHOD_MERGE.equals(request.getMethod())) { DAVResourceURI tmp = new DAVResourceURI(null, myResourcePathInfo, null, false); path = DAVPathUtil.standardize(tmp.getPath()); } boolean checkDestinationPath = false; String destinationPath = null; if (DAVHandlerFactory.METHOD_MOVE.equals(request.getMethod()) || DAVHandlerFactory.METHOD_COPY.equals(request.getMethod())) { String destinationURL = request.getHeader(DESTINATION_HEADER); if (destinationURL == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Destination path missing"), SVNLogType.NETWORK); } destinationPath = DAVPathUtil.standardize(getRepositoryRelativePath(SVNURL.parseURIEncoded(destinationURL))); checkDestinationPath = true; } String repository = getResourceRepositoryName(request.getPathInfo()); String user = request.getRemoteUser(); int access = getRequestedAccess(request.getMethod()); checkAccess(repository, path, checkDestinationPath, destinationPath, user, access); } } private int getRequestedAccess(String method) { int access = SVNPathBasedAccess.SVN_ACCESS_NONE; if (DAVHandlerFactory.METHOD_COPY.equals(method) || DAVHandlerFactory.METHOD_MOVE.equals(method) || DAVHandlerFactory.METHOD_DELETE.equals(method)) { access |= SVNPathBasedAccess.SVN_ACCESS_RECURSIVE; } else if (DAVHandlerFactory.METHOD_OPTIONS.equals(method) || DAVHandlerFactory.METHOD_PROPFIND.equals(method) || DAVHandlerFactory.METHOD_GET.equals(method) || DAVHandlerFactory.METHOD_REPORT.equals(method)) { access |= SVNPathBasedAccess.SVN_ACCESS_READ; } else if (DAVHandlerFactory.METHOD_MKCOL.equals(method) || DAVHandlerFactory.METHOD_PUT.equals(method) || DAVHandlerFactory.METHOD_PROPPATCH.equals(method) || DAVHandlerFactory.METHOD_CHECKOUT.equals(method) || DAVHandlerFactory.METHOD_MERGE.equals(method) || DAVHandlerFactory.METHOD_MKACTIVITY.equals(method) || DAVHandlerFactory.METHOD_LOCK.equals(method) || DAVHandlerFactory.METHOD_UNLOCK.equals(method)) { access |= SVNPathBasedAccess.SVN_ACCESS_WRITE; } else { access |= SVNPathBasedAccess.SVN_ACCESS_RECURSIVE | SVNPathBasedAccess.SVN_ACCESS_WRITE; } return access; } private void checkAccess(String repository, String path, boolean checkDestinationPath, String destinationPath, String user, int access) throws SVNException { if (getDAVConfig().getSVNAccess() == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "An error occured while loading configuration file."), SVNLogType.NETWORK); } if (!getDAVConfig().isAnonymousAllowed() && user == null) { SVNErrorManager.authenticationFailed("Anonymous user is not allowed on resource", null); } if (path != null || (path == null && (access & SVNPathBasedAccess.SVN_ACCESS_WRITE) != SVNPathBasedAccess.SVN_ACCESS_NONE)) { if (!getDAVConfig().getSVNAccess().checkAccess(repository, path, user, access)) { if (user == null) { SVNErrorManager.authenticationFailed("Forbidden for anonymous", null); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.NO_AUTH_FILE_PATH), SVNLogType.NETWORK); } } } if (checkDestinationPath) { if (path != null) { if (!getDAVConfig().getSVNAccess().checkAccess(repository, destinationPath, user, access)) { if (user == null) { SVNErrorManager.authenticationFailed("Forbidden for anonymous", null); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.NO_AUTH_FILE_PATH), SVNLogType.NETWORK); } } } } } public DAVConfig getDAVConfig() { return myDAVConfig; } public String getResourceRepositoryRoot() { return myResourceRepositoryRoot; } public String getResourceContext() { return myResourceContext; } public String getResourcePathInfo() { return myResourcePathInfo; } public SVNURL convertHttpToFile(SVNURL url) throws SVNException { String uri = DAVPathUtil.addLeadingSlash(url.getURIEncodedPath()); if (!uri.startsWith(getResourceContext())) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Invalid URL ''{0}'' requested", url.toString()), SVNLogType.NETWORK); } return SVNURL.parseURIEncoded(getResourceRepositoryRoot() + getRepositoryRelativePath(url)); } public String getRepositoryRelativePath(SVNURL url) throws SVNException { String uri = getURI(url); DAVResourceURI resourceURI = new DAVResourceURI(null, uri, null, false); return resourceURI.getPath(); } public String getURI(SVNURL url) throws SVNException { String uri = DAVPathUtil.addLeadingSlash(url.getURIEncodedPath()); if (uri.startsWith(getResourceContext())) { uri = uri.substring(getResourceContext().length()); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Invalid URL ''{0}'' requested", url.toString()), SVNLogType.NETWORK); } return uri; } public DAVResource getRequestedDAVResource(boolean isSVNClient, String deltaBase, String pathInfo, long version, String clientOptions, String baseChecksum, String resultChecksum, String label, boolean useCheckedIn, List lockTokens, Map capabilities) throws SVNException { pathInfo = pathInfo == null ? getResourcePathInfo() : pathInfo; DAVResourceURI resourceURI = new DAVResourceURI(getResourceContext(), pathInfo, label, useCheckedIn); DAVConfig config = getDAVConfig(); String fsParentPath = config.getRepositoryParentPath(); String xsltURI = config.getXSLTIndex(); String reposName = config.getRepositoryName(); String uri = resourceURI.getURI(); if (fsParentPath != null && getDAVConfig().isListParentPath()) { if (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); } //TODO: later add code for parent path resource here } SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "uri type - " + resourceURI.getType() + ", uri kind - " + resourceURI.getKind()); String activitiesDB = config.getActivitiesDBPath(); File activitiesDBDir = null; if (activitiesDB == null) { activitiesDBDir = new File(myRepositoryRootDir, DEFAULT_ACTIVITY_DB); } else { activitiesDBDir = new File(activitiesDB); } String userName = myUserPrincipal != null ? myUserPrincipal.getName() : null; SVNAuthentication auth = new SVNUserNameAuthentication(userName, false, null, false); BasicAuthenticationManager authManager = new BasicAuthenticationManager(new SVNAuthentication[] { auth }); SVNRepository resourceRepository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(getResourceRepositoryRoot())); resourceRepository.setAuthenticationManager(authManager); DAVResource resource = new DAVResource(resourceRepository, this, resourceURI, isSVNClient, deltaBase, version, clientOptions, baseChecksum, resultChecksum, userName, activitiesDBDir, lockTokens, capabilities); return resource; } private String getRepositoryRoot(String requestURI) { StringBuffer repositoryURL = new StringBuffer(); repositoryURL.append(FILE_PROTOCOL_LINE); if (getDAVConfig().isUsingRepositoryPathDirective()) { repositoryURL.append(getDAVConfig().getRepositoryPath().startsWith("/") ? "" : "/"); repositoryURL.append(getDAVConfig().getRepositoryPath()); } else { String reposParentPath = getDAVConfig().getRepositoryParentPath(); if (!reposParentPath.startsWith("/")) { reposParentPath = "/" + reposParentPath; } repositoryURL.append(DAVPathUtil.addTrailingSlash(reposParentPath)); repositoryURL.append(DAVPathUtil.head(requestURI)); } return repositoryURL.toString(); } private File getRepositoryRootDir(String requestURI) { File reposRootDir = null; if (getDAVConfig().isUsingRepositoryPathDirective()) { reposRootDir = new File(getDAVConfig().getRepositoryPath()); } else { reposRootDir = new File(getDAVConfig().getRepositoryParentPath(), DAVPathUtil.head(requestURI)); } return reposRootDir; } private String getResourcePathInfo(HttpServletRequest request) throws SVNException { String pathInfo = request.getPathInfo(); if (pathInfo == null || "".equals(pathInfo)) { pathInfo = "/"; } if (getDAVConfig().isUsingRepositoryPathDirective()) { return pathInfo; } if (pathInfo == null || pathInfo.length() == 0 || "/".equals(pathInfo)) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED), SVNLogType.NETWORK); //TODO: client tried to access repository parent path, result status code should be FORBIDDEN. } return DAVPathUtil.removeHead(pathInfo, true); } private String getResourceRepositoryName(String requestURI) { if (getDAVConfig().isUsingRepositoryPathDirective()) { return ""; } return DAVPathUtil.head(requestURI); } private String getResourceContext(HttpServletRequest request) { String requestContext = request.getContextPath(); String pathInfo = request.getPathInfo(); String servletPath = request.getServletPath(); if (getDAVConfig().isUsingRepositoryPathDirective()) { if (servletPath != null && !"".equals(servletPath)) { if (servletPath.startsWith("/")) { servletPath = servletPath.substring(1); } requestContext = SVNPathUtil.append(requestContext, servletPath); } return SVNEncodingUtil.uriEncode(requestContext); } String reposName = DAVPathUtil.head(pathInfo); if (servletPath != null && !"".equals(servletPath)) { if (servletPath.startsWith("/")) { servletPath = servletPath.substring(1); } String pathToRepos = SVNPathUtil.append(requestContext, servletPath); requestContext = SVNPathUtil.append(pathToRepos, reposName); return SVNEncodingUtil.uriEncode(requestContext); } requestContext = DAVPathUtil.append(requestContext, reposName); return SVNEncodingUtil.uriEncode(requestContext); } } DAVResource.java000066400000000000000000000530721177510526000336530ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.File; import java.io.OutputStream; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.ISVNDirEntryHandler; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionNode; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVResource { public static final long INVALID_REVISION = SVNRepository.INVALID_REVISION; public static final String DEFAULT_COLLECTION_CONTENT_TYPE = "text/html; charset=\"utf-8\""; public static final String DEFAULT_FILE_CONTENT_TYPE = "text/plain"; private DAVRepositoryManager myRepositoryManager; private DAVResourceURI myResourceURI; private FSRepository myRepository; private long myRevision; private long myVersion; private boolean myIsCollection; private boolean myIsSVNClient; private boolean myIsAutoCheckedOut; private String myDeltaBase; private String myClientOptions; private String myBaseChecksum; private String myResultChecksum; private String myUserName; private SVNProperties mySVNProperties; private Collection myDeadProperties; private Collection myEntries; private File myActivitiesDB; private FSFS myFSFS; private String myTxnName; private FSRoot myRoot; private FSTransactionInfo myTxnInfo; private Map myClientCapabilities; private Collection myLockTokens; /** * DAVResource constructor * * @param repository repository resource connect to * @param context contains requested url requestContext and name of repository if servlet use SVNParentPath directive. * @param uri special uri for DAV requests can be /path or /SPECIAL_URI/xxx/path * @param label request's label header * @param useCheckedIn special case for VCC resource * @throws SVNException if an error occurs while fetching repository properties. */ public DAVResource(SVNRepository repository, DAVRepositoryManager manager, DAVResourceURI resourceURI, boolean isSVNClient, String deltaBase, long version, String clientOptions, String baseChecksum, String resultChecksum, String userName, File activitiesDB, Collection lockTokens, Map clientCapabilities) throws DAVException { myRepositoryManager = manager; myRepository = (FSRepository) repository; try { myRepository.testConnection();//this should create an FSFS object } catch (SVNException svne) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.FSFS, svne.getMessage()); SVNErrorMessage err = SVNErrorMessage.create(svne.getErrorMessage().getErrorCode(), "Could not open the requested SVN filesystem"); throw DAVException.convertError(err, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not fetch resource information.", null); } myLockTokens = lockTokens; myClientCapabilities = clientCapabilities; myFSFS = myRepository.getFSFS(); myResourceURI = resourceURI; myIsSVNClient = isSVNClient; myDeltaBase = deltaBase; myVersion = version; myClientOptions = clientOptions; myBaseChecksum = baseChecksum; myResultChecksum = resultChecksum; myRevision = resourceURI.getRevision(); myUserName = userName; myActivitiesDB = activitiesDB; DAVResourceHelper.prepareResource(this); } public DAVResource(DAVRepositoryManager manager, SVNRepository repository, DAVResourceURI resourceURI, long revision, boolean isSVNClient, String deltaBase, long version, String clientOptions, String baseChecksum, String resultChecksum, String userName, File activitiesDB, Collection lockTokens, Map clientCapabilities) { myRepositoryManager = manager; myResourceURI = resourceURI; myRepository = (FSRepository) repository; myFSFS = myRepository.getFSFS(); myRevision = revision; myIsSVNClient = isSVNClient; myDeltaBase = deltaBase; myVersion = version; myClientOptions = clientOptions; myBaseChecksum = baseChecksum; myResultChecksum = resultChecksum; myUserName = userName; myActivitiesDB = activitiesDB; myLockTokens = lockTokens; myClientCapabilities = clientCapabilities; } public DAVResource() { } public void setRoot(FSRoot root) { myRoot = root; } public FSRoot getRoot() { return myRoot; } public FSTransactionInfo getTxnInfo() { return myTxnInfo; } public void setTxnInfo(FSTransactionInfo txnInfo) { myTxnInfo = txnInfo; } public DAVResourceURI getResourceURI() { return myResourceURI; } public SVNRepository getRepository() { return myRepository; } public long getRevision() { return myRevision; } public boolean exists() { return myResourceURI.exists(); } public boolean isVersioned() { return myResourceURI.isVersioned(); } public boolean isWorking() { return myResourceURI.isWorking(); } public boolean isBaseLined() { return myResourceURI.isBaseLined(); } public DAVResourceType getType() { return getResourceURI().getType(); } //TODO: refactor DAVResourceKind later and name //this method as getPrivateResourceKind() public DAVResourceKind getKind() { return getResourceURI().getKind(); } public String getActivityID() { return myResourceURI.getActivityID(); } public boolean lacksETagPotential() { DAVResourceType type = getResourceURI().getType(); return !exists() || (type != DAVResourceType.REGULAR && type != DAVResourceType.VERSION) || (type == DAVResourceType.VERSION && isBaseLined()); } public boolean canBeActivity() { return isAutoCheckedOut() || (getType() == DAVResourceType.ACTIVITY && !exists()); } public boolean isCollection() { return myIsCollection; } public boolean isSVNClient() { return myIsSVNClient; } public DAVAutoVersion getAutoVersion() { if (getType() == DAVResourceType.VERSION && isBaseLined()) { return DAVAutoVersion.ALWAYS; } DAVConfig config = myRepositoryManager.getDAVConfig(); if (config.isAutoVersioning()) { if (getType() == DAVResourceType.REGULAR) { return DAVAutoVersion.ALWAYS; } if (getType() == DAVResourceType.WORKING && isAutoCheckedOut()) { return DAVAutoVersion.ALWAYS; } } return DAVAutoVersion.NEVER; } public String getUserName() { return myUserName; } public String getDeltaBase() { return myDeltaBase; } public long getVersion() { return myVersion; } public String getClientOptions() { return myClientOptions; } public String getBaseChecksum() { return myBaseChecksum; } public String getResultChecksum() { return myResultChecksum; } public File getActivitiesDB() { return myActivitiesDB; } public void versionControl(String target) throws DAVException { if (exists()) { throw new DAVException("vsn_control called on already-versioned resource.", HttpServletResponse.SC_BAD_REQUEST, 0); } if (target != null) { throw new DAVException("vsn_control called with non-null target.", null, HttpServletResponse.SC_NOT_IMPLEMENTED, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } } public Iterator getChildren() throws SVNException { return new Iterator() { Iterator entriesIterator = getEntries().iterator(); public void remove() { } public boolean hasNext() { return entriesIterator.hasNext(); } public Object next() { SVNDirEntry entry = (SVNDirEntry) entriesIterator.next(); String childURI = DAVPathUtil.append(getResourceURI().getURI(), entry.getName()); try { DAVResourceURI newResourceURI = new DAVResourceURI(getResourceURI().getContext(), childURI, null, false); return new DAVResource(myRepositoryManager, getRepository(), newResourceURI, getRevision(), isSVNClient(), getDeltaBase(), getVersion(), getClientOptions(), null, null, getUserName(), getActivitiesDB(), getLockTokens(), getClientCapabilities()); } catch (SVNException e) { return null; } } }; } public Map getClientCapabilities() { return myClientCapabilities; } public Collection getLockTokens() { return myLockTokens; } public void setLockTokens(Collection lockTokens) { if (myLockTokens != null) { myLockTokens.addAll(lockTokens); } myLockTokens = lockTokens; } public Collection getEntries() throws SVNException { if (isCollection() && myEntries == null) { myEntries = new LinkedList(); getRepository().getDir(getResourceURI().getPath(), getRevision(), null, SVNDirEntry.DIRENT_KIND, myEntries); } return myEntries; } public long getCreatedRevision() throws SVNException { String revisionParameter = getProperty(SVNProperty.COMMITTED_REVISION); try { return Long.parseLong(revisionParameter); } catch (NumberFormatException e) { return getRevision(); } } public long getCreatedRevisionUsingFS(String path) throws SVNException { path = path == null ? getResourceURI().getPath() : path; FSRevisionNode node = myRoot.getRevisionNode(path); return node.getCreatedRevision(); } public Date getLastModified() throws SVNException { if (lacksETagPotential()) { return null; } return getRevisionDate(getCreatedRevision()); } public Date getRevisionDate(long revision) throws SVNException { //TODO: insert here later an authz check return SVNDate.parseDate(getRevisionProperty(revision, SVNRevisionProperty.DATE)); } public String getETag() { if (lacksETagPotential()) { return null; } long createdRevision = -1; try { createdRevision = getCreatedRevisionUsingFS(null); } catch (SVNException svne) { return null; } StringBuffer eTag = new StringBuffer(); eTag.append(isCollection() ? "W/" : ""); eTag.append("\""); eTag.append(createdRevision); eTag.append("/"); eTag.append(SVNEncodingUtil.xmlEncodeCDATA(getResourceURI().getPath(), true)); eTag.append("\""); return eTag.toString(); } public String getRepositoryUUID(boolean forceConnect) throws SVNException { return getRepository().getRepositoryUUID(forceConnect); } public String getContentType() throws SVNException { if (getResourceURI().isBaseLined() && getResourceURI().getType() == DAVResourceType.VERSION) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_PROPS_NOT_FOUND, "Failed to determine property"), SVNLogType.NETWORK); return null; } if (getResourceURI().getType() == DAVResourceType.PRIVATE && getResourceURI().getKind() == DAVResourceKind.VCC) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_PROPS_NOT_FOUND, "Failed to determine property"), SVNLogType.NETWORK); return null; } if (isCollection()) { return DEFAULT_COLLECTION_CONTENT_TYPE; } String contentType = getProperty(SVNProperty.MIME_TYPE); if (contentType != null) { return contentType; } return DEFAULT_FILE_CONTENT_TYPE; } public long getLatestRevision() throws SVNException { return getRepository().getLatestRevision(); } //TODO: remove this method later, use getContentLength(String path) instead /** * @deprecated */ public long getContentLength() throws SVNException { SVNDirEntry entry = getRepository().getDir(getResourceURI().getPath(), getRevision(), false, null); return entry.getSize(); } public long getContentLength(String path) throws SVNException { path = path == null ? getResourceURI().getPath() : path; FSRevisionNode node = myRoot.getRevisionNode(path); return node.getFileLength(); } public SVNLock[] getLocks() throws SVNException { if (getResourceURI().getPath() == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "get-locks-report run on resource which doesn't represent a path within a repository."), SVNLogType.NETWORK); } return getRepository().getLocks(getResourceURI().getPath()); } public SVNLock getLock() throws SVNException { return getRepository().getLock(getResourceURI().getPath()); } public void unlock(String token, boolean force) throws SVNException { Map pathsToTokens = new HashMap(); pathsToTokens.put(getResourceURI().getPath(), token); getRepository().unlock(pathsToTokens, force, null); } public String getAuthor(long revision) throws SVNException { return getRevisionProperty(revision, SVNRevisionProperty.AUTHOR); } /** * @deprecated use getMD5Checksum() instead */ public String getMD5Checksum() throws SVNException { return getProperty(SVNProperty.CHECKSUM); } public String getMD5Checksum(String path) throws SVNException { path = path == null ? getResourceURI().getPath() : path; FSRevisionNode node = myRoot.getRevisionNode(path); return node.getFileMD5Checksum(); } public String getLog(long revision) throws SVNException { return getRevisionProperty(revision, SVNRevisionProperty.LOG); } //TODO: replace later with getProperty(path, propName) /** * @deprecated */ public String getProperty(String propertyName) throws SVNException { return getSVNProperties().getStringValue(propertyName); } public SVNPropertyValue getProperty(String path, String propertyName) throws SVNException { return getSVNProperties(path).getSVNPropertyValue(propertyName); } public String getRevisionProperty(long revision, String propertyName) throws SVNException { SVNPropertyValue value = getRepository().getRevisionPropertyValue(revision, propertyName); return value == null ? null : value.getString(); } public void writeTo(OutputStream out) throws SVNException { if (isCollection()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED), SVNLogType.NETWORK); } getRepository().getFile(getResourceURI().getPath(), getRevision(), null, out); } public boolean isAutoCheckedOut() { return myIsAutoCheckedOut; } public void setIsAutoCkeckedOut(boolean isAutoCheckedOut) { myIsAutoCheckedOut = isAutoCheckedOut; } public String getTxnName() { return myTxnName; } public void setExists(boolean exists) { myResourceURI.setExists(exists); } public void setVersioned(boolean isVersioned) { myResourceURI.setVersioned(isVersioned); } public void setWorking(boolean isWorking) { myResourceURI.setWorking(isWorking); } public void setBaseLined(boolean isBaseLined) { myResourceURI.setBaseLined(isBaseLined); } public void setCollection(boolean isCollection) { myIsCollection = isCollection; } public void setTxnName(String txnName) { myTxnName = txnName; } public void setRevision(long revision) { myRevision = revision; myResourceURI.setRevision(revision); } public void setResourceURI(DAVResourceURI resourceURI) { myResourceURI = resourceURI; } public boolean equals(Object o) { if (o == null || o.getClass() != this.getClass()) { return false; } if (o == this) { return true; } DAVResource otherResource = (DAVResource) o; if (!isOurResource(otherResource)) { return false; } String myRequestURI = myResourceURI.getRequestURI(); String otherRequestURI = otherResource.getResourceURI().getRequestURI(); return myRequestURI.equals(otherRequestURI); } public DAVResource dup() { DAVResource copy = new DAVResource(); copyTo(copy); return copy; } public FSFS getFSFS() { return myFSFS; } public DAVRepositoryManager getRepositoryManager() { return myRepositoryManager; } public boolean isParentResource(DAVResource resource) { if (!isOurResource(resource)) { return false; } String thisURIPath = myResourceURI.getURI(); String otherURIPath = resource.getResourceURI().getURI(); return otherURIPath.length() > thisURIPath.length() && otherURIPath.startsWith(thisURIPath) && otherURIPath.charAt(thisURIPath.length()) == '/'; } public SVNProperties getSVNProperties(String path) throws SVNException { path = path == null ? getResourceURI().getPath() : path; if (mySVNProperties == null) { mySVNProperties = myFSFS.getProperties(myRoot.getRevisionNode(path)); } return mySVNProperties; } private boolean isOurResource(DAVResource resource) { File reposRoot1 = myFSFS.getDBRoot(); File reposRoot2 = resource.myFSFS.getDBRoot(); if (!reposRoot1.equals(reposRoot2)) { return false; } return true; } //TODO: replace occurances of getSVNProperties() with getSVNProperties(path) /** * @deprecated */ public SVNProperties getSVNProperties() throws SVNException { if (mySVNProperties == null) { mySVNProperties = new SVNProperties(); if (getResourceURI().getType() == DAVResourceType.REGULAR) { if (isCollection()) { getRepository().getDir(getResourceURI().getPath(), getRevision(), mySVNProperties, (ISVNDirEntryHandler) null); } else { getRepository().getFile(getResourceURI().getPath(), getRevision(), mySVNProperties, null); } } } return mySVNProperties; } protected void copyTo(DAVResource copy) { copy.myRepositoryManager = myRepositoryManager; copy.myResourceURI = myResourceURI.dup(); copy.myRepository = myRepository; copy.myRevision = myRevision; copy.myIsCollection = myIsCollection; copy.myIsSVNClient = myIsCollection; copy.myIsAutoCheckedOut = myIsAutoCheckedOut; copy.myDeltaBase = myDeltaBase; copy.myVersion = myVersion; copy.myClientOptions = myClientOptions; copy.myBaseChecksum = myBaseChecksum; copy.myResultChecksum = myResultChecksum; copy.myUserName = myUserName; copy.mySVNProperties = mySVNProperties; copy.myDeadProperties = myDeadProperties; copy.myEntries = myEntries; copy.myActivitiesDB = myActivitiesDB; copy.myFSFS = myFSFS; copy.myTxnName = myTxnName; copy.myRoot = myRoot; copy.myTxnInfo = myTxnInfo; copy.myClientCapabilities = myClientCapabilities; copy.myLockTokens = myLockTokens; } } DAVResourceHelper.java000066400000000000000000000137771177510526000350230ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.server.dav.handlers.DAVLockInfoProvider; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public abstract class DAVResourceHelper { private static final Map ourResourceHelpers = new HashMap(); static { registerHelper(DAVResourceType.WORKING, new DAVWorkingResourceHelper()); registerHelper(DAVResourceType.REGULAR, new DAVRegularResourceHelper()); registerHelper(DAVResourceType.ACTIVITY, new DAVActivityResourceHelper()); registerHelper(DAVResourceType.HISTORY, new DAVHistoryResourceHelper()); registerHelper(DAVResourceType.PRIVATE, new DAVPrivateResourceHelper()); registerHelper(DAVResourceType.VERSION, new DAVVersionResourceHelper()); } protected abstract void prepare(DAVResource resource) throws DAVException; protected abstract DAVResource getParentResource(DAVResource resource) throws DAVException; public static void prepareResource(DAVResource resource) throws DAVException { DAVResourceURI resourceURI = resource.getResourceURI(); DAVResourceType resourceType = resourceURI.getType(); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "resource type is " + resourceType.toString()); DAVResourceHelper helperImpl = getHelper(resourceType); helperImpl.prepare(resource); } public static DAVResource createParentResource(DAVResource resource) throws DAVException { DAVResourceURI resourceURI = resource.getResourceURI(); DAVResourceType resourceType = resourceURI.getType(); DAVResourceHelper helperImpl = getHelper(resourceType); return helperImpl.getParentResource(resource); } public static DAVResource getDirectResource(DAVLockInfoProvider lockProvider, String lockToken, DAVResource resource) throws DAVException { while (resource != null) { DAVLock lock = lockProvider.findLock(resource, lockToken); if (lock == null) { throw new DAVException("The specified locktoken does not correspond to an existing lock on this resource.", HttpServletResponse.SC_BAD_REQUEST, 0); } if (lock.getRecType() == DAVLockRecType.DIRECT) { return resource; } resource = createParentResource(resource); } throw new DAVException("The lock database is corrupt. A direct lock could not be found for the corresponding indirect lock on this resource.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } public static void throwIllegalGetParentResourceError(DAVResource resource) throws DAVException { DAVResourceURI uri = resource.getResourceURI(); throw new DAVException("getParentResource() was called for {0} (type {1})", new Object[] { uri.getRequestURI(), uri.getType() }, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } public static void convertWorkingToRegular(DAVResource resource) throws DAVException { DAVResourceURI uri = resource.getResourceURI(); uri.setType(DAVResourceType.REGULAR); resource.setWorking(false); String path = null; FSFS fsfs = resource.getFSFS(); if (!SVNRevision.isValidRevisionNumber(resource.getRevision())) { long rev = SVNRepository.INVALID_REVISION; try { rev = resource.getLatestRevision(); } catch (SVNException e) { throw DAVException.convertError(e.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not determine youngest rev.", null); } resource.setRevision(rev); path = uri.getPath(); } else { path = DAVPathUtil.buildURI(uri.getContext(), DAVResourceKind.BASELINE_COLL, resource.getRevision(), uri.getPath(), false); } path = SVNEncodingUtil.uriEncode(path); uri.setURI(path); try { resource.setRoot(fsfs.createRevisionRoot(resource.getRevision())); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open revision root.", null); } } private static DAVResourceHelper getHelper(DAVResourceType resourceType) throws DAVException { DAVResourceHelper helperImpl = (DAVResourceHelper) ourResourceHelpers.get(resourceType); if (helperImpl == null) { throw new DAVException("DESIGN FAILURE: unknown resource type", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } return helperImpl; } protected synchronized static void registerHelper(DAVResourceType resourceType, DAVResourceHelper factoryImpl) { ourResourceHelpers.put(resourceType, factoryImpl); } } DAVResourceKind.java000066400000000000000000000046001177510526000344520ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVResourceKind { public static final DAVResourceKind ACT_COLLECTION = new DAVResourceKind("act"); public static final DAVResourceKind BASELINE = new DAVResourceKind("bln"); public static final DAVResourceKind BASELINE_COLL = new DAVResourceKind("bc"); public static final DAVResourceKind HISTORY = new DAVResourceKind("his"); public static final DAVResourceKind WORKING = new DAVResourceKind("wrk"); public static final DAVResourceKind PUBLIC = new DAVResourceKind(""); public static final DAVResourceKind VERSION = new DAVResourceKind("ver"); public static final DAVResourceKind VCC = new DAVResourceKind("vcc"); public static final DAVResourceKind WRK_BASELINE = new DAVResourceKind("wbl"); public static final DAVResourceKind ROOT_COLLECTION = new DAVResourceKind("rc"); public static final DAVResourceKind UNKNOWN = new DAVResourceKind(null); private String myKind; private DAVResourceKind(String kind) { myKind = kind; } public String toString() { return myKind; } public static DAVResourceKind parseKind(String kind) { if ("act".equals(kind)) { return ACT_COLLECTION; } else if ("bln".equals(kind)) { return BASELINE; } else if ("bc".equals(kind)) { return BASELINE_COLL; } else if ("".equals(kind)) { return PUBLIC; } else if ("ver".equals(kind)) { return VERSION; } else if ("his".equals(kind)) { return HISTORY; } else if ("wrk".equals(kind)) { return WORKING; } else if ("wbl".equals(kind)) { return WRK_BASELINE; } else if ("vcc".equals(kind)) { return VCC; } return UNKNOWN; } } DAVResourceState.java000066400000000000000000000021511177510526000346440ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVResourceState { public final static DAVResourceState NULL = new DAVResourceState(11); public final static DAVResourceState LOCK_NULL = new DAVResourceState(10); public final static DAVResourceState EXISTS = new DAVResourceState(12); public final static DAVResourceState ERROR = new DAVResourceState(13); private int myID; private DAVResourceState(int id) { myID = id; } public int getID() { return myID; } } DAVResourceType.java000066400000000000000000000026061177510526000345120ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVResourceType { public static final DAVResourceType REGULAR = new DAVResourceType("regular"); public static final DAVResourceType WORKING = new DAVResourceType("working"); public static final DAVResourceType VERSION = new DAVResourceType("version"); public static final DAVResourceType PRIVATE = new DAVResourceType("private"); public static final DAVResourceType ACTIVITY = new DAVResourceType("activity"); public static final DAVResourceType HISTORY = new DAVResourceType("history"); public static final DAVResourceType WORKSPACE = new DAVResourceType("workspace"); private String myName; private DAVResourceType(String name) { myName = name; } public String toString() { return myName; } } DAVResourceURI.java000066400000000000000000000305741177510526000342350ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVResourceURI { public static final String SPECIAL_URI = "!svn"; public static final String DEDAULT_VCC_NAME = "default"; private String myURI; private String myContext; private DAVResourceType myType; private DAVResourceKind myKind; private long myRevision; private String myPath; private String myActivityID; private boolean myIsExists = false; private boolean myIsVersioned = false; private boolean myIsBaseLined = false; private boolean myIsWorking = false; public DAVResourceURI(String context, String uri, String label, boolean useCheckedIn) throws SVNException { StringBuffer logBuffer = new StringBuffer(); logBuffer.append('\n'); logBuffer.append("uri: " + uri); logBuffer.append('\n'); logBuffer.append("label: " + label); logBuffer.append('\n'); logBuffer.append("context: " + context); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, logBuffer.toString()); myURI = uri == null ? "" : uri; myContext = context; myRevision = DAVResource.INVALID_REVISION; parseURI(label, useCheckedIn); logBuffer.delete(0, logBuffer.length()); logBuffer.append('\n'); logBuffer.append("DAVResourceURI.getRequestURI(): " + getRequestURI()); logBuffer.append('\n'); logBuffer.append("DAVResourceURI.getURI(): " + getURI()); logBuffer.append('\n'); logBuffer.append("DAVResourceURI.getPath(): " + getPath()); logBuffer.append('\n'); logBuffer.append("DAVResourceURI.getContext(): " + getContext()); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, logBuffer.toString()); } public DAVResourceURI(String context, String uri, String path, long revision, DAVResourceKind kind, DAVResourceType type, String activityID, boolean exists, boolean isVersioned, boolean isBaseLined, boolean isWorking) { myContext = context; myURI = uri; myPath = path; myActivityID = activityID; myRevision = revision; myType = type; myKind = kind; myIsExists = exists; myIsVersioned = isVersioned; myIsBaseLined = isBaseLined; myIsWorking = isWorking; } public DAVResourceURI() { } public DAVResourceURI dup() { return new DAVResourceURI(myContext, myURI, myPath, myRevision, myKind, myType, myActivityID, myIsExists, myIsVersioned, myIsBaseLined, myIsWorking); } public String getRequestURI() { return SVNPathUtil.append(getContext(), getURI()); } public String getContext() { return myContext; } public String getURI() { return myURI; } public void setURI(String uri) { myURI = uri; } public DAVResourceType getType() { return myType; } public DAVResourceKind getKind() { return myKind; } public long getRevision() { return myRevision; } public String getPath() { return myPath; } public String getActivityID() { return myActivityID; } public boolean exists() { return myIsExists; } public boolean isVersioned() { return myIsVersioned; } public boolean isBaseLined() { return myIsBaseLined; } public boolean isWorking() { return myIsWorking; } public void setExists(boolean isExist) { myIsExists = isExist; } public void setPath(String path) { myPath = DAVPathUtil.standardize(path); } public void setVersioned(boolean isVersioned) { myIsVersioned = isVersioned; } public void setKind(DAVResourceKind kind) { myKind = kind; } public void setType(DAVResourceType type) { myType = type; } public void setRevision(long revisionNumber) { myRevision = revisionNumber; } public void setWorking(boolean isWorking) { myIsWorking = isWorking; } public void setActivityID(String activityID) { myActivityID = activityID; } public void setBaseLined(boolean isBaseLined) { myIsBaseLined = isBaseLined; } private void parseURI(String label, boolean useCheckedIn) throws SVNException { if (!SPECIAL_URI.equals(DAVPathUtil.head(getURI()))) { setKind(DAVResourceKind.PUBLIC); setType(DAVResourceType.REGULAR); setPath(getURI()); setVersioned(true); } else { String specialPart = DAVPathUtil.removeHead(getURI(), false); if (specialPart.length() == 0) { // root/!svn setType(DAVResourceType.PRIVATE); setKind(DAVResourceKind.ROOT_COLLECTION); } else { specialPart = DAVPathUtil.dropLeadingSlash(specialPart); if (!specialPart.endsWith("/") && SVNPathUtil.getSegmentsCount(specialPart) == 1) { // root/!svn/XXX setType(DAVResourceType.PRIVATE); } else { DAVResourceKind kind = DAVResourceKind.parseKind(DAVPathUtil.head(specialPart)); if (kind != DAVResourceKind.UNKNOWN) { setKind(kind); String parameter = DAVPathUtil.removeHead(specialPart, false); parameter = DAVPathUtil.dropLeadingSlash(parameter); if (kind == DAVResourceKind.VCC) { parseVCC(parameter, label, useCheckedIn); } else if (kind == DAVResourceKind.VERSION) { parseVersion(parameter); } else if (kind == DAVResourceKind.BASELINE) { parseBaseline(parameter); } else if (kind == DAVResourceKind.BASELINE_COLL) { parseBaselineCollection(parameter); } else if (kind == DAVResourceKind.ACT_COLLECTION) { parseActivity(parameter); } else if (kind == DAVResourceKind.HISTORY) { parseHistory(parameter); } else if (kind == DAVResourceKind.WRK_BASELINE) { parseWorkingBaseline(parameter); } else if (kind == DAVResourceKind.WORKING) { parseWorking(parameter); } } } } } } private void parseWorking(String parameter) { setType(DAVResourceType.WORKING); setVersioned(true); setWorking(true); if (SVNPathUtil.getSegmentsCount(parameter) == 1) { setActivityID(parameter); setPath("/"); } else { setActivityID(DAVPathUtil.head(parameter)); setPath(DAVPathUtil.removeHead(parameter, false)); } } private void parseWorkingBaseline(String parameter) throws SVNException { setType(DAVResourceType.WORKING); setWorking(true); setVersioned(true); setBaseLined(true); if (SVNPathUtil.getSegmentsCount(parameter) == 1) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "Invalid URI ''{0}''", getRequestURI()), SVNLogType.NETWORK); } setActivityID(DAVPathUtil.head(parameter)); try { String revisionParameter = DAVPathUtil.removeHead(parameter, false); long revision = Long.parseLong(DAVPathUtil.dropLeadingSlash(revisionParameter)); setRevision(revision); } catch (NumberFormatException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, e), e, SVNLogType.NETWORK); } } private void parseHistory(String parameter) { setType(DAVResourceType.HISTORY); setPath(parameter); } private void parseActivity(String parameter) { setType(DAVResourceType.ACTIVITY); setActivityID(parameter); } private void parseBaselineCollection(String parameter) throws SVNException { long revision = DAVResource.INVALID_REVISION; String parameterPath; if (SVNPathUtil.getSegmentsCount(parameter) == 1) { parameterPath = "/"; try { revision = Long.parseLong(parameter); } catch (NumberFormatException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, e.getMessage()), e, SVNLogType.NETWORK); } } else { try { revision = Long.parseLong(DAVPathUtil.head(parameter)); } catch (NumberFormatException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, e.getMessage()), e, SVNLogType.NETWORK); } parameterPath = DAVPathUtil.removeHead(parameter, false); } setType(DAVResourceType.REGULAR); setVersioned(true); setRevision(revision); setPath(parameterPath); } private void parseBaseline(String parameter) throws SVNException { try { setRevision(Long.parseLong(parameter)); } catch (NumberFormatException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, e.getMessage()), e, SVNLogType.NETWORK); } setVersioned(true); setBaseLined(true); setType(DAVResourceType.VERSION); } private void parseVersion(String parameter) throws SVNException { setVersioned(true); setType(DAVResourceType.VERSION); if (SVNPathUtil.getSegmentsCount(parameter) == 1) { try { setRevision(Long.parseLong(parameter)); } catch (NumberFormatException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "Invalid URI ''{0}''", e.getMessage()), e, SVNLogType.NETWORK); } setPath("/"); } else { try { setRevision(Long.parseLong(DAVPathUtil.head(parameter))); } catch (NumberFormatException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, e.getMessage()), e, SVNLogType.NETWORK); } setPath(DAVPathUtil.removeHead(parameter, false)); } } private void parseVCC(String parameter, String label, boolean useCheckedIn) throws SVNException { if (!DEDAULT_VCC_NAME.equals(parameter)) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Invalid VCC name ''{0}''", parameter), SVNLogType.NETWORK); } if (label == null && !useCheckedIn) { setType(DAVResourceType.PRIVATE); setExists(true); setVersioned(true); setBaseLined(true); } else { long revision = DAVResource.INVALID_REVISION; if (label != null) { try { revision = Long.parseLong(label); } catch (NumberFormatException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "Invalid label header ''{0}''", label), SVNLogType.NETWORK); } } setType(DAVResourceType.VERSION); setRevision(revision); setVersioned(true); setBaseLined(true); setPath(null); } } } DAVServlet.java000066400000000000000000000362731177510526000335140ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory; import org.tmatesoft.svn.core.internal.server.dav.handlers.DAVHandlerFactory; import org.tmatesoft.svn.core.internal.server.dav.handlers.DAVResponse; import org.tmatesoft.svn.core.internal.server.dav.handlers.ServletDAVHandler; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVServlet extends HttpServlet { public static final String XML_CONTENT_TYPE = "text/xml; charset=\"utf-8\""; public static final String DAV_SVN_AUTOVERSIONING_ACTIVITY = "svn-autoversioning-activity"; private static final Map OUR_STATUS_LINES = new SVNHashMap(); private static final Map OUR_SHARED_CACHE = new SVNHashMap(); static { OUR_STATUS_LINES.put(new Integer(100), "100 Continue"); OUR_STATUS_LINES.put(new Integer(101), "101 Switching Protocols"); OUR_STATUS_LINES.put(new Integer(102), "102 Processing"); OUR_STATUS_LINES.put(new Integer(200), "200 OK"); OUR_STATUS_LINES.put(new Integer(201), "201 Created"); OUR_STATUS_LINES.put(new Integer(202), "202 Accepted"); OUR_STATUS_LINES.put(new Integer(203), "203 Non-Authoritative Information"); OUR_STATUS_LINES.put(new Integer(204), "204 No Content"); OUR_STATUS_LINES.put(new Integer(205), "205 Reset Content"); OUR_STATUS_LINES.put(new Integer(206), "206 Partial Content"); OUR_STATUS_LINES.put(new Integer(207), "207 Multi-Status"); OUR_STATUS_LINES.put(new Integer(300), "300 Multiple Choices"); OUR_STATUS_LINES.put(new Integer(301), "301 Moved Permanently"); OUR_STATUS_LINES.put(new Integer(302), "302 Found"); OUR_STATUS_LINES.put(new Integer(303), "303 See Other"); OUR_STATUS_LINES.put(new Integer(304), "304 Not Modified"); OUR_STATUS_LINES.put(new Integer(305), "305 Use Proxy"); OUR_STATUS_LINES.put(new Integer(306), "306 unused"); OUR_STATUS_LINES.put(new Integer(307), "307 Temporary Redirect"); OUR_STATUS_LINES.put(new Integer(400), "400 Bad Request"); OUR_STATUS_LINES.put(new Integer(401), "401 Authorization Required"); OUR_STATUS_LINES.put(new Integer(402), "402 Payment Required"); OUR_STATUS_LINES.put(new Integer(403), "403 Forbidden"); OUR_STATUS_LINES.put(new Integer(404), "404 Not Found"); OUR_STATUS_LINES.put(new Integer(405), "405 Method Not Allowed"); OUR_STATUS_LINES.put(new Integer(406), "406 Not Acceptable"); OUR_STATUS_LINES.put(new Integer(407), "407 Proxy Authentication Required"); OUR_STATUS_LINES.put(new Integer(408), "408 Request Time-out"); OUR_STATUS_LINES.put(new Integer(409), "409 Conflict"); OUR_STATUS_LINES.put(new Integer(410), "410 Gone"); OUR_STATUS_LINES.put(new Integer(411), "411 Length Required"); OUR_STATUS_LINES.put(new Integer(412), "412 Precondition Failed"); OUR_STATUS_LINES.put(new Integer(413), "413 Request Entity Too Large"); OUR_STATUS_LINES.put(new Integer(414), "414 Request-URI Too Large"); OUR_STATUS_LINES.put(new Integer(415), "415 Unsupported Media Type"); OUR_STATUS_LINES.put(new Integer(416), "416 Requested Range Not Satisfiable"); OUR_STATUS_LINES.put(new Integer(417), "417 Expectation Failed"); OUR_STATUS_LINES.put(new Integer(418), "418 unused"); OUR_STATUS_LINES.put(new Integer(419), "419 unused"); OUR_STATUS_LINES.put(new Integer(420), "420 unused"); OUR_STATUS_LINES.put(new Integer(421), "421 unused"); OUR_STATUS_LINES.put(new Integer(422), "422 Unprocessable Entity"); OUR_STATUS_LINES.put(new Integer(423), "423 Locked"); OUR_STATUS_LINES.put(new Integer(424), "424 Failed Dependency"); OUR_STATUS_LINES.put(new Integer(425), "425 No code"); OUR_STATUS_LINES.put(new Integer(426), "426 Upgrade Required"); OUR_STATUS_LINES.put(new Integer(500), "500 Internal Server Error"); OUR_STATUS_LINES.put(new Integer(501), "501 Method Not Implemented"); OUR_STATUS_LINES.put(new Integer(502), "502 Bad Gateway"); OUR_STATUS_LINES.put(new Integer(503), "503 Service Temporarily Unavailable"); OUR_STATUS_LINES.put(new Integer(504), "504 Gateway Time-out"); OUR_STATUS_LINES.put(new Integer(505), "505 HTTP Version Not Supported"); OUR_STATUS_LINES.put(new Integer(506), "506 Variant Also Negotiates"); OUR_STATUS_LINES.put(new Integer(507), "507 Insufficient Storage"); OUR_STATUS_LINES.put(new Integer(508), "508 unused"); OUR_STATUS_LINES.put(new Integer(509), "509 unused"); OUR_STATUS_LINES.put(new Integer(510), "510 Not Extended"); } private DAVConfig myDAVConfig; private DAVConfig getDAVConfig() { return myDAVConfig; } public void init() { FSRepositoryFactory.setup(); try { myDAVConfig = new DAVConfig(getServletConfig()); } catch (SVNException e) { myDAVConfig = null; } } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletDAVHandler handler = null; logRequest(request);//TODO: remove later try { DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request); handler = DAVHandlerFactory.createHandler(repositoryManager, request, response); handler.execute(); } catch (DAVException de) { response.setContentType(XML_CONTENT_TYPE); handleError(de, response); } catch (SVNException svne) { StringWriter sw = new StringWriter(); svne.printStackTrace(new PrintWriter(sw)); String msg = sw.getBuffer().toString(); SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode(); if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) { response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) { response.sendError(HttpServletResponse.SC_FORBIDDEN, msg); } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg); } else { String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null, svne.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType(XML_CONTENT_TYPE); response.getWriter().print(errorBody); } } catch (Throwable th) { StringWriter sw = new StringWriter(); th.printStackTrace(new PrintWriter(sw)); String msg = sw.getBuffer().toString(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } finally { response.flushBuffer(); } } private void logRequest(HttpServletRequest request) { StringBuffer logBuffer = new StringBuffer(); logBuffer.append('\n'); logBuffer.append("request.getAuthType(): " + request.getAuthType()); logBuffer.append('\n'); logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding()); logBuffer.append('\n'); logBuffer.append("request.getContentType(): " + request.getContentType()); logBuffer.append('\n'); logBuffer.append("request.getContextPath(): " + request.getContextPath()); logBuffer.append('\n'); logBuffer.append("request.getContentLength(): " + request.getContentLength()); logBuffer.append('\n'); logBuffer.append("request.getMethod(): " + request.getMethod()); logBuffer.append('\n'); logBuffer.append("request.getPathInfo(): " + request.getPathInfo()); logBuffer.append('\n'); logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated()); logBuffer.append('\n'); logBuffer.append("request.getQueryString(): " + request.getQueryString()); logBuffer.append('\n'); logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr()); logBuffer.append('\n'); logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost()); logBuffer.append('\n'); logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser()); logBuffer.append('\n'); logBuffer.append("request.getRequestURI(): " + request.getRequestURI()); logBuffer.append('\n'); logBuffer.append("request.getServerName(): " + request.getServerName()); logBuffer.append('\n'); logBuffer.append("request.getServerPort(): " + request.getServerPort()); logBuffer.append('\n'); logBuffer.append("request.getServletPath(): " + request.getServletPath()); logBuffer.append('\n'); logBuffer.append("request.getRequestURL(): " + request.getRequestURL()); SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, logBuffer.toString()); } public static void handleError(DAVException error, HttpServletResponse servletResponse) throws IOException { SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, error); DAVResponse response = error.getResponse(); if (response == null) { DAVException stackErr = error; while (stackErr != null && stackErr.getTagName() == null) { stackErr = stackErr.getPreviousException(); } if (stackErr != null && stackErr.getTagName() != null) { servletResponse.setContentType(XML_CONTENT_TYPE); servletResponse.setStatus(stackErr.getResponseCode()); StringBuffer errorMessageBuffer = new StringBuffer(); SVNXMLUtil.addXMLHeader(errorMessageBuffer); errorMessageBuffer.append('\n'); errorMessageBuffer.append("\n"); } else { errorMessageBuffer.append(">\n"); } if (stackErr.getMessage() != null) { errorMessageBuffer.append("\n"); errorMessageBuffer.append(SVNEncodingUtil.xmlEncodeCDATA(stackErr.getMessage())); errorMessageBuffer.append('\n'); errorMessageBuffer.append("\n"); } errorMessageBuffer.append("\n"); servletResponse.getWriter().print(errorMessageBuffer.toString()); SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, errorMessageBuffer.toString()); return; } servletResponse.setStatus(error.getResponseCode()); return; } DAVXMLUtil.sendMultiStatus(response, servletResponse, error.getResponseCode(), null); } private String generateStandardizedErrorBody(int errorID, String namespace, String tagName, String description) { StringBuffer xmlBuffer = new StringBuffer(); SVNXMLUtil.addXMLHeader(xmlBuffer); Collection namespaces = new ArrayList(); namespaces.add(DAVElement.DAV_NAMESPACE); namespaces.add(DAVElement.SVN_APACHE_PROPERTY_NAMESPACE); if (namespace != null) { namespaces.add(namespace); } SVNXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVXMLUtil.SVN_DAV_ERROR_TAG, namespaces, SVNXMLUtil.PREFIX_MAP, xmlBuffer); String prefix = (String) SVNXMLUtil.PREFIX_MAP.get(namespace); if (prefix != null) { prefix = SVNXMLUtil.DAV_NAMESPACE_PREFIX; } if (tagName != null && tagName.length() > 0) { SVNXMLUtil.openXMLTag(prefix, tagName, SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, xmlBuffer); } SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_APACHE_PROPERTY_PREFIX, "human-readable", SVNXMLUtil.XML_STYLE_NORMAL, "errcode", String.valueOf(errorID), xmlBuffer); xmlBuffer.append(SVNEncodingUtil.xmlEncodeCDATA(description)); SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_APACHE_PROPERTY_PREFIX, "human-readable", xmlBuffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVXMLUtil.SVN_DAV_ERROR_TAG, xmlBuffer); return xmlBuffer.toString(); } public static String getStatusLine(int statusCode) { return (String) OUR_STATUS_LINES.get(new Integer(statusCode)); } public static String getSharedActivity() { synchronized (OUR_SHARED_CACHE) { return (String) OUR_SHARED_CACHE.get(DAV_SVN_AUTOVERSIONING_ACTIVITY); } } public static void setSharedActivity(String sharedActivity) { synchronized (OUR_SHARED_CACHE) { OUR_SHARED_CACHE.put(DAV_SVN_AUTOVERSIONING_ACTIVITY, sharedActivity); } } public static boolean isHTTPServerError(int statusCode) { return statusCode >= 500 && statusCode < 600; } }DAVServletUtil.java000066400000000000000000000465451177510526000343550ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.io.fs.FSCommitter; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSID; import org.tmatesoft.svn.core.internal.io.fs.FSNodeHistory; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionNode; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionRoot; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionRoot; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVServletUtil { public static long getSafeCreatedRevision(FSRevisionRoot root, String path) { long revision = root.getRevision(); FSFS fsfs = root.getOwner(); FSID id = null; try { FSRevisionNode node = root.getRevisionNode(path); id = node.getId(); } catch (SVNException svne) { return revision; } FSNodeHistory history = null; long historyRev = -1; try { history = root.getNodeHistory(path); history = history.getPreviousHistory(false); historyRev = history.getHistoryEntry().getRevision(); } catch (SVNException svne) { return revision; } FSRevisionRoot otherRoot = null; try { otherRoot = fsfs.createRevisionRoot(historyRev); } catch (SVNException svne) { return revision; } FSID otherID = null; try { FSRevisionNode node = otherRoot.getRevisionNode(path); otherID = node.getId(); } catch (SVNException svne) { return revision; } if (id.compareTo(otherID) == 0) { return historyRev; } return revision; } public static URI lookUpURI(String uri, HttpServletRequest request, boolean mustBeAbsolute) throws DAVException { URI parsedURI = null; try { parsedURI = new URI(uri); } catch (URISyntaxException urise) { throw new DAVException("Invalid syntax in Destination URI.", HttpServletResponse.SC_BAD_REQUEST, 0); } if (parsedURI.getScheme() == null && mustBeAbsolute) { throw new DAVException("Destination URI must be an absolute URI.", HttpServletResponse.SC_BAD_REQUEST, 0); } if (parsedURI.getQuery() != null || parsedURI.getFragment() != null) { throw new DAVException("Destination URI contains invalid components (a query or a fragment).", HttpServletResponse.SC_BAD_REQUEST, 0); } if (parsedURI.getScheme() != null || parsedURI.getPort() != -1 || mustBeAbsolute) { String scheme = request.getScheme(); if (scheme == null) { //TODO: replace this code in future scheme = "http"; } int parsedPort = parsedURI.getPort(); if (parsedURI.getPort() == -1) { parsedPort = request.getServerPort(); } if (!scheme.equals(parsedURI.getScheme()) || parsedPort != request.getServerPort()) { throw new DAVException("Destination URI refers to different scheme or port ({0}://hostname:{1})\n(want: {2}://hostname:{3})", new Object[] { parsedURI.getScheme() != null ? parsedURI.getScheme() : scheme, String.valueOf(parsedPort), scheme, String.valueOf(request.getServerPort()) }, HttpServletResponse.SC_BAD_REQUEST, 0); } } String parsedHost = parsedURI.getHost(); String serverHost = request.getServerName(); String domain = null; int domainInd = serverHost != null ? serverHost.indexOf('.') : -1; if (domainInd != -1) { domain = serverHost.substring(domainInd); } if (parsedHost != null && parsedHost.indexOf('.') == -1 && domain != null) { parsedHost += domain; } if (parsedHost != null && !parsedHost.equals(request.getServerName())) { throw new DAVException("Destination URI refers to a different server.", HttpServletResponse.SC_BAD_GATEWAY, 0); } return parsedURI; } public static void setAutoRevisionProperties(DAVResource resource) throws DAVException { if (!(resource.getType() == DAVResourceType.WORKING && resource.isAutoCheckedOut())) { throw new DAVException("Set_auto_revprops called on invalid resource.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } try { attachAutoRevisionProperties(resource.getTxnInfo(), resource.getResourceURI().getPath(), resource.getFSFS()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error setting a revision property ", null); } } public static void attachAutoRevisionProperties(FSTransactionInfo txn, String path, FSFS fsfs) throws SVNException { String logMessage = "Autoversioning commit: a non-deltaV client made a change to\n" + path; SVNProperties props = new SVNProperties(); props.put(SVNRevisionProperty.LOG, logMessage); props.put(SVNRevisionProperty.AUTOVERSIONED, "*"); fsfs.changeTransactionProperties(txn.getTxnId(), props); } public static void deleteActivity(DAVResource resource, String activityID) throws DAVException { File activitiesDB = resource.getActivitiesDB(); String txnName = getTxn(activitiesDB, activityID); if (txnName == null) { throw new DAVException("could not find activity.", HttpServletResponse.SC_NOT_FOUND, 0); } FSFS fsfs = resource.getFSFS(); FSTransactionInfo txn = null; if (txnName != null) { try { txn = fsfs.openTxn(txnName); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() != SVNErrorCode.FS_NO_SUCH_TRANSACTION) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not open transaction.", null); } } if (txn != null) { try { FSCommitter.abortTransaction(fsfs, txn.getTxnId()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not abort transaction.", null); } } } try { SVNFileUtil.deleteFile(DAVPathUtil.getActivityPath(activitiesDB, activityID)); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to remove activity.", null); } } public static void storeActivity(DAVResource resource, String txnName) throws DAVException { DAVResourceURI resourceURI = resource.getResourceURI(); String activityID = resourceURI.getActivityID(); File activitiesDB = resource.getActivitiesDB(); if (!activitiesDB.exists() && !activitiesDB.mkdirs()) { throw new DAVException("could not initialize activity db.", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } File finalActivityFile = DAVPathUtil.getActivityPath(activitiesDB, activityID); File tmpFile = null; try { tmpFile = SVNFileUtil.createUniqueFile(finalActivityFile.getParentFile(), finalActivityFile.getName(), "tmp", false); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Can't open activity db"); throw DAVException.convertError(err, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not open files.", null); } StringBuffer activitiesContents = new StringBuffer(); activitiesContents.append(txnName); activitiesContents.append('\n'); activitiesContents.append(activityID); activitiesContents.append('\n'); try { SVNFileUtil.writeToFile(tmpFile, activitiesContents.toString(), null); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Can't write to activity db"); try { SVNFileUtil.deleteFile(tmpFile); } catch (SVNException e) { } throw DAVException.convertError(err, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not write files.", null); } try { SVNFileUtil.rename(tmpFile, finalActivityFile); } catch (SVNException svne) { try { SVNFileUtil.deleteFile(tmpFile); } catch (SVNException e) { } throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not replace files.", null); } } public static FSTransactionInfo createActivity(DAVResource resource, FSFS fsfs) throws DAVException { SVNProperties properties = new SVNProperties(); properties.put(SVNRevisionProperty.AUTHOR, resource.getUserName()); long revision = SVNRepository.INVALID_REVISION; try { revision = fsfs.getYoungestRevision(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not determine youngest revision", null); } FSTransactionInfo txnInfo = null; try { txnInfo = FSTransactionRoot.beginTransactionForCommit(revision, properties, fsfs); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not begin a transaction", null); } return txnInfo; } public static LinkedList processIfHeader(String value) throws DAVException { if (value == null) { return null; } StringBuffer valueBuffer = new StringBuffer(value); ListType listType = ListType.UNKNOWN; String uri = null; LinkedList ifHeaders = new LinkedList(); DAVIFHeader ifHeader = null; while (valueBuffer.length() > 0) { if (valueBuffer.charAt(0) == '<') { if (listType == ListType.NO_TAGGED || (uri = DAVServletUtil.fetchNextToken(valueBuffer, '>')) == null) { throw new DAVException("Invalid If-header: unclosed \"<\" or unexpected tagged-list production.", HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_TAGGED); } URI parsedURI = null; try { parsedURI = new URI(uri); } catch (URISyntaxException urise) { throw new DAVException("Invalid URI in tagged If-header.", HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_TAGGED); } uri = parsedURI.getPath(); uri = uri.length() > 1 && uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri; listType = ListType.TAGGED; } else if (valueBuffer.charAt(0) == '(') { if (listType == ListType.UNKNOWN) { listType = ListType.NO_TAGGED; } StringBuffer listBuffer = null; String list = null; if ((list = DAVServletUtil.fetchNextToken(valueBuffer, ')')) == null) { throw new DAVException("Invalid If-header: unclosed \"(\".", HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_UNCLOSED_PAREN); } ifHeader = new DAVIFHeader(uri); ifHeaders.addFirst(ifHeader); int condition = DAVIFState.IF_CONDITION_NORMAL; String stateToken = null; listBuffer = new StringBuffer(list); while (listBuffer.length() > 0) { if (listBuffer.charAt(0) == '<') { if ((stateToken = DAVServletUtil.fetchNextToken(listBuffer, '>')) == null) { throw new DAVException(null, HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_PARSE); } addIfState(stateToken, DAVIFStateType.IF_OPAQUE_LOCK, condition, ifHeader); condition = DAVIFState.IF_CONDITION_NORMAL; } else if (listBuffer.charAt(0) == '[') { if ((stateToken = fetchNextToken(listBuffer, ']')) == null) { throw new DAVException(null, HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_PARSE); } addIfState(stateToken, DAVIFStateType.IF_ETAG, condition, ifHeader); condition = DAVIFState.IF_CONDITION_NORMAL; } else if (listBuffer.charAt(0) == 'N') { if (listBuffer.length() > 2 && listBuffer.charAt(1) == 'o' && listBuffer.charAt(2) == 't') { if (condition != DAVIFState.IF_CONDITION_NORMAL) { throw new DAVException("Invalid \"If:\" header: Multiple \"not\" entries for the same state.", HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_MULTIPLE_NOT); } condition = DAVIFState.IF_CONDITION_NOT; } listBuffer.delete(0, 2); } else if (listBuffer.charAt(0) != ' ' && listBuffer.charAt(0) != '\t') { throw new DAVException("Invalid \"If:\" header: Unexpected character encountered ({0}, ''{1}'').", new Object[] { Integer.toHexString(listBuffer.charAt(0)), new Character(listBuffer.charAt(0)) }, HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_UNK_CHAR); } listBuffer.deleteCharAt(0); } } else if (valueBuffer.charAt(0) != ' ' && valueBuffer.charAt(0) != '\t') { throw new DAVException("Invalid \"If:\" header: Unexpected character encountered ({0}, ''{1}'').", new Object[] { Integer.toHexString(valueBuffer.charAt(0)), new Character(valueBuffer.charAt(0)) }, HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.IF_UNK_CHAR); } valueBuffer.deleteCharAt(0); } return ifHeaders; } public static FSTransactionInfo openTxn(FSFS fsfs, String txnName) throws DAVException { FSTransactionInfo txnInfo = null; try { txnInfo = fsfs.openTxn(txnName); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NO_SUCH_TRANSACTION) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The transaction specified by the activity does not exist", null); } throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "There was a problem opening the transaction specified by this activity.", null); } return txnInfo; } public static String getTxn(File activitiesDB, String activityID) { File activityFile = DAVPathUtil.getActivityPath(activitiesDB, activityID); return DAVServletUtil.readTxn(activityFile); } public static String readTxn(File activityFile) { String txnName = null; for (int i = 0; i < 10; i++) { try { txnName = SVNFileUtil.readSingleLine(activityFile); } catch (IOException e) { //ignore } } return txnName; } public static SVNNodeKind checkPath(FSRoot root, String path) throws DAVException { try { return root.checkNodeKind(path); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NOT_DIRECTORY) { return SVNNodeKind.NONE; } throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error checking kind of path ''{0}'' in repository", new Object[] { path }); } } private static void addIfState(String stateToken, DAVIFStateType type, int condition, DAVIFHeader ifHeader) { String eTag = null; String lockToken = null; if (type == DAVIFStateType.IF_OPAQUE_LOCK) { lockToken = stateToken; } else { eTag = stateToken; } DAVIFState ifState = new DAVIFState(condition, eTag, lockToken, type); ifHeader.addIFState(ifState); } private static String fetchNextToken(StringBuffer string, char term) { String token = string.substring(1); token = token.trim(); int ind = -1; if ((ind = token.indexOf(term)) == -1) { return null; } token = token.substring(0, ind); string.delete(0, string.indexOf(token) + token.length()); return token; } private static class ListType { public static final ListType NO_TAGGED = new ListType(); public static final ListType TAGGED = new ListType(); public static final ListType UNKNOWN = new ListType(); private ListType() { } } } DAVURIInfo.java000066400000000000000000000022501177510526000333270ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVURIInfo { private long myRevision; private String myActivityID; private String myRepositoryPath; public DAVURIInfo(String activityID, String repositoryPath, long revision) { myActivityID = activityID; myRepositoryPath = repositoryPath; myRevision = revision; } public long getRevision() { return myRevision; } public String getActivityID() { return myActivityID; } public String getRepositoryPath() { return myRepositoryPath; } } DAVVersionResourceHelper.java000066400000000000000000000063761177510526000363660ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.wc.SVNRevision; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVVersionResourceHelper extends DAVResourceHelper { protected void prepare(DAVResource resource) throws DAVException { if (!SVNRevision.isValidRevisionNumber(resource.getRevision())) { try { resource.setRevision(resource.getLatestRevision()); } catch (SVNException e) { throw DAVException.convertError(e.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not fetch 'youngest' revision to enable accessing the latest baseline resource.", null); } } FSRoot root = resource.getRoot(); FSFS fsfs = resource.getFSFS(); if (root == null) { try { root = fsfs.createRevisionRoot(resource.getRevision()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open a revision root.", null); } resource.setRoot(root); } resource.getResourceURI().setURI(DAVPathUtil.buildURI(null, DAVResourceKind.BASELINE, resource.getRevision(), null, false)); resource.setExists(true); } protected DAVResource getParentResource(DAVResource resource) throws DAVException { DAVResourceHelper.throwIllegalGetParentResourceError(resource); return null; } public static DAVResource createVersionResource(DAVResource resource, String uri) throws DAVException { DAVResourceURI regularResourceURI = null; try { regularResourceURI = new DAVResourceURI(resource.getResourceURI().getContext(), uri, null, false); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not parse version resource uri.", null); } return new DAVResource(resource.getRepository(), resource.getRepositoryManager(), regularResourceURI, resource.isSVNClient(), resource.getDeltaBase(), resource.getVersion(), resource.getClientOptions(), resource.getBaseChecksum(), resource.getResultChecksum(), resource.getUserName(), resource.getActivitiesDB(), resource.getLockTokens(), resource.getClientCapabilities()); } } DAVWorkingResourceHelper.java000066400000000000000000000146271177510526000363570ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVWorkingResourceHelper extends DAVResourceHelper { protected void prepare(DAVResource resource) throws DAVException { String txnName = DAVServletUtil.getTxn(resource.getActivitiesDB(), resource.getResourceURI().getActivityID()); if (txnName == null) { throw new DAVException("An unknown activity was specified in the URL. This is generally caused by a problem in the client software.", null, HttpServletResponse.SC_BAD_REQUEST, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } resource.setTxnName(txnName); FSFS fsfs = resource.getFSFS(); FSTransactionInfo txnInfo = null; try { txnInfo = fsfs.openTxn(txnName); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NO_SUCH_TRANSACTION) { throw new DAVException("An activity was specified and found, but the corresponding SVN FS transaction was not found.", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An activity was specified and found, but the corresponding SVN FS transaction was not found.", null); } resource.setTxnInfo(txnInfo); if (resource.isBaseLined()) { resource.setExists(true); return; } String userName = resource.getUserName(); if (resource.getUserName() != null) { SVNProperties props = null; try { props = fsfs.getTransactionProperties(txnName); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve author of the SVN FS transaction corresponding to the specified activity.", null); } String currentAuthor = props.getStringValue(SVNRevisionProperty.AUTHOR); if (currentAuthor == null) { try { fsfs.setTransactionProperty(txnName, SVNRevisionProperty.AUTHOR, SVNPropertyValue.create(userName)); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to set the author of the SVN FS transaction corresponding to the specified activity.", null); } } else if (!currentAuthor.equals(userName)) { throw new DAVException("Multi-author commits not supported.", null, HttpServletResponse.SC_NOT_IMPLEMENTED, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } } FSRoot root = null; try { root = fsfs.createTransactionRoot(txnInfo); resource.setRoot(root); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open the (transaction) root of the repository", null); } SVNNodeKind kind = DAVServletUtil.checkPath(root, resource.getResourceURI().getPath()); resource.setExists(kind != SVNNodeKind.NONE); resource.setCollection(kind == SVNNodeKind.DIR); } protected DAVResource getParentResource(DAVResource resource) throws DAVException { return DAVPrivateResourceHelper.createPrivateResource(resource, DAVResourceKind.WORKING); } public static DAVResource createWorkingResource(DAVResource baseResource, String activityID, String txnName, boolean inPlace) { StringBuffer pathBuffer = new StringBuffer(); if (baseResource.isBaseLined()) { pathBuffer.append('/'); pathBuffer.append(DAVResourceURI.SPECIAL_URI); pathBuffer.append("/wbl/"); pathBuffer.append(activityID); pathBuffer.append('/'); pathBuffer.append(baseResource.getRevision()); } else { pathBuffer.append('/'); pathBuffer.append(DAVResourceURI.SPECIAL_URI); pathBuffer.append("/wrk/"); pathBuffer.append(activityID); pathBuffer.append(baseResource.getResourceURI().getPath()); } String uriPath = SVNEncodingUtil.uriEncode(pathBuffer.toString()); DAVResource resource = null; if (inPlace) { resource = baseResource; } else { resource = new DAVResource(); baseResource.copyTo(resource); } resource.setTxnName(txnName); resource.setExists(true); resource.setVersioned(true); resource.setWorking(true); DAVResourceURI uri = resource.getResourceURI(); uri.setType(DAVResourceType.WORKING); uri.setURI(uriPath); uri.setActivityID(activityID); return resource; } } DAVXMLUtil.java000066400000000000000000000177471177510526000333730ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.handlers.DAVPropsResult; import org.tmatesoft.svn.core.internal.server.dav.handlers.DAVResponse; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVXMLUtil extends SVNXMLUtil { public static final String SVN_DAV_ERROR_TAG = "error"; public static StringBuffer addEmptyElement(List namespaces, DAVElement element, StringBuffer target) { if (element.getNamespace() == null || "".equals(element.getNamespace())) { target.append("<"); target.append(element.getName()); target.append("/>"); target.append('\n'); return target; } int index = namespaces.indexOf(element.getNamespace()); target.append(""); return target; } public static StringBuffer openNamespaceDeclarationTag(String prefix, String header, Collection namespaces, StringBuffer target, boolean useIndexedPrefixes) { return openNamespaceDeclarationTag(prefix, header, namespaces, null, target, true, useIndexedPrefixes); } public static StringBuffer openNamespaceDeclarationTag(String prefix, String header, Collection namespaces, Map attrs, StringBuffer target, boolean addEOL, boolean useIndexedPrefixes) { target = target == null ? new StringBuffer() : target; target.append("<"); target.append(prefix); target.append(":"); target.append(header); //We should always add "DAV:" namespace target.append(" xmlns:"); target.append(DAV_NAMESPACE_PREFIX); target.append("=\""); target.append(DAVElement.DAV_NAMESPACE); target.append("\""); if (namespaces != null && !namespaces.isEmpty()) { Collection usedNamespaces = new ArrayList(); usedNamespaces.add(DAVElement.DAV_NAMESPACE); int i = 0; for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { Object item = iterator.next(); String currentNamespace = null; if (item instanceof DAVElement) { DAVElement currentElement = (DAVElement) item; currentNamespace = currentElement.getNamespace(); } else if (item instanceof String) { currentNamespace = (String) item; } if (currentNamespace != null && currentNamespace.length() > 0 && (useIndexedPrefixes || !usedNamespaces.contains(currentNamespace))) { usedNamespaces.add(currentNamespace); target.append(" xmlns:"); if (useIndexedPrefixes) { target.append("ns" + i); } else { target.append(PREFIX_MAP.get(currentNamespace)); } target.append("=\""); target.append(currentNamespace); target.append("\""); } i++; } usedNamespaces.clear(); } if (attrs != null && !attrs.isEmpty()) { for (Iterator iterator = attrs.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); String value = (String) entry.getValue(); target.append(" "); target.append(name); target.append("=\""); target.append(SVNEncodingUtil.xmlEncodeAttr(value)); target.append("\""); } } target.append(">"); if (addEOL) { target.append('\n'); } return target; } public static StringBuffer beginMultiStatus(HttpServletResponse servletResponse, int status, Collection namespaces, StringBuffer xmlBuffer) { servletResponse.setContentType(DAVServlet.XML_CONTENT_TYPE); servletResponse.setStatus(status); xmlBuffer = xmlBuffer == null ? new StringBuffer() : xmlBuffer; SVNXMLUtil.addXMLHeader(xmlBuffer); DAVXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.MULTISTATUS.getName(), namespaces, xmlBuffer, namespaces != null); return xmlBuffer; } public static void sendMultiStatus(DAVResponse davResponse, HttpServletResponse servletResponse, int statusCode, Collection namespaces) throws IOException { StringBuffer xmlBuffer = new StringBuffer(); xmlBuffer = beginMultiStatus(servletResponse, statusCode, namespaces, xmlBuffer); while (davResponse != null) { sendOneResponse(davResponse, xmlBuffer); davResponse = davResponse.getNextResponse(); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.MULTISTATUS.getName(), xmlBuffer); servletResponse.getWriter().write(xmlBuffer.toString()); } public static void sendOneResponse(DAVResponse davResponse, StringBuffer xmlBuffer) { DAVPropsResult propResult = davResponse.getPropResult(); Collection namespaces = propResult.getNamespaces(); if (namespaces == null || namespaces.isEmpty()) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, xmlBuffer); } else { xmlBuffer.append('<'); xmlBuffer.append(SVNXMLUtil.DAV_NAMESPACE_PREFIX); xmlBuffer.append(':'); xmlBuffer.append(DAVElement.RESPONSE.getName()); for (Iterator namespacesIter = namespaces.iterator(); namespacesIter.hasNext();) { String namespaceText = (String) namespacesIter.next(); xmlBuffer.append(namespaceText); } xmlBuffer.append(">\n"); } String href = davResponse.getHref(); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), href, null, true, true, xmlBuffer); String propStatsText = propResult.getPropStatsText(); if (propStatsText == null || propStatsText.length() == 0) { String statusLine = "HTTP/1.1 " + DAVServlet.getStatusLine(davResponse.getStatusCode()); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), statusLine, null, false, false, xmlBuffer); } else { xmlBuffer.append(propStatsText); } if (davResponse.getDescription() != null) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE_DESCRIPTION.getName(), davResponse.getDescription(), null, false, false, xmlBuffer); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE.getName(), xmlBuffer); } } SVNPathBasedAccess.java000066400000000000000000000660331177510526000350760ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.admin.SVNTranslatorInputStream; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class SVNPathBasedAccess { private static final Pattern COMMA = Pattern.compile(","); private static final String ANONYMOUS_REPOSITORY = ""; public static final int SVN_ACCESS_NONE = 0; public static final int SVN_ACCESS_READ = 1; public static final int SVN_ACCESS_WRITE = 2; public static final int SVN_ACCESS_RECURSIVE = 4; private String myConfigPath; private int myCurrentLineNumber = 1; private int myCurrentLineColumn = 0; private char myUngottenChar = 0; private boolean myHasUngottenChar = false; private StringBuffer mySectionName; private StringBuffer myOption; private StringBuffer myValue; private Map myGroups; private Map myAliases; private Map myRules; public SVNPathBasedAccess(File pathBasedAccessConfiguration) throws SVNException { myConfigPath = pathBasedAccessConfiguration.getAbsolutePath(); InputStream stream = null; try { stream = new SVNTranslatorInputStream(SVNFileUtil.openFileForReading(pathBasedAccessConfiguration, SVNLogType.NETWORK), SVNProperty.EOL_LF_BYTES, true, null, false); } catch (SVNException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "Failed to load the AuthzSVNAccessFile: ''{0}''", pathBasedAccessConfiguration.getAbsolutePath()), SVNLogType.NETWORK); } try { parse(stream); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage()), SVNLogType.NETWORK); } validate(); } private String getConfigPath() { return myConfigPath; } private void increaseCurrentLineNumber() { myCurrentLineNumber++; } private int getCurrentLineNumber() { return myCurrentLineNumber; } private void increaseCurrentLineColumn() { myCurrentLineColumn++; } private void resetCurrentLineColumn() { myCurrentLineColumn = 0; } private int getCurrentLineColumn() { return myCurrentLineColumn; } private char getUngottenChar() { return myUngottenChar; } private void setUngottenChar(char ungottenChar) { myUngottenChar = ungottenChar; } private boolean hasUngottenChar() { return myHasUngottenChar; } private void setHasUngottenChar(boolean hasUngottenChar) { myHasUngottenChar = hasUngottenChar; } private StringBuffer getSectionName() { if (mySectionName == null) { mySectionName = new StringBuffer(); } return mySectionName; } private StringBuffer getOption() { if (myOption == null) { myOption = new StringBuffer(); } return myOption; } private StringBuffer getValue() { if (myValue == null) { myValue = new StringBuffer(); } return myValue; } private Map getGroups() { if (myGroups == null) { myGroups = new SVNHashMap(); } return myGroups; } private boolean groupContainsUser(String group, String user) { String[] groupUsers = (String[]) getGroups().get(group); if (groupUsers == null) { return false; } for (int i = 0; i < groupUsers.length; i++) { if (groupUsers[i].startsWith("@")) { if (groupContainsUser(groupUsers[i].substring("@".length()), user)) { return true; } } else if (groupUsers[i].startsWith("&")) { if (aliasIsUser(groupUsers[i].substring("&".length()), user)) { return true; } } else if (groupUsers[i].equals(user)) { return true; } } return false; } private Map getAliases() { if (myAliases == null) { myAliases = new SVNHashMap(); } return myAliases; } private boolean aliasIsUser(String alias, String user) { String aliasValue = (String) getAliases().get(alias); return aliasValue != null && aliasValue.equals(user); } private Map getRules() { if (myRules == null) { myRules = new SVNHashMap(); } return myRules; } public boolean checkAccess(String repository, String path, String user, int access) { RepositoryAccess repositoryAccess = (RepositoryAccess) getRules().get(repository); if (repositoryAccess == null) { repositoryAccess = (SVNPathBasedAccess.RepositoryAccess) getRules().get(ANONYMOUS_REPOSITORY); if (repositoryAccess == null) { return false; } } return repositoryAccess.checkPathAccess(path, user, access); } private void parse(InputStream is) throws IOException, SVNException { boolean isEOF = false; int currentByte; do { currentByte = skipWhitespace(is); switch (currentByte) { case'[': if (getCurrentLineColumn() == 0) { parseSectionName(is); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "''{0}'' : ''{1}'' : Section header must start in the first column.", new Object[]{getConfigPath(), new Integer(getCurrentLineNumber())}), SVNLogType.NETWORK); } break; case'#': if (getCurrentLineColumn() == 0) { skipToEndOfLine(is); increaseCurrentLineNumber(); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "''{0}'' : ''{1}'' : Comment must start in the first column.", new Object[]{getConfigPath(), new Integer(getCurrentLineNumber())}), SVNLogType.NETWORK); } break; case'\n': increaseCurrentLineNumber(); break; case-1: isEOF = true; break; default: if (getSectionName().length() == 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "''{0}'' : ''{1}'' : Section header expected.", new Object[]{getConfigPath(), new Integer(getCurrentLineNumber())}), SVNLogType.NETWORK); } else if (getCurrentLineColumn() != 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "''{0}'' : ''{1}'' : Option expected.", new Object[]{getConfigPath(), new Integer(getCurrentLineNumber())}), SVNLogType.NETWORK); } else { parseOption(is, currentByte); } } } while (!isEOF); getSectionName().setLength(0); getOption().setLength(0); getValue().setLength(0); } private int parseSectionName(InputStream is) throws IOException, SVNException { getSectionName().setLength(0); int currentByte = getc(is); while (currentByte != -1 && currentByte != '\n' && currentByte != ']') { getSectionName().append((char) currentByte); currentByte = getc(is); } if (currentByte != ']') { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "''{0}'' : ''{1}'' : Section header must end with ']'.", new Object[]{getConfigPath(), new Integer(getCurrentLineNumber())}), SVNLogType.NETWORK); } else { currentByte = skipToEndOfLine(is); if (currentByte != -1) { increaseCurrentLineNumber(); } } return currentByte; } private int parseOption(InputStream is, int firstByte) throws IOException, SVNException { getOption().setLength(0); int currentByte = firstByte; while (currentByte != -1 && currentByte != ':' && currentByte != '=' && currentByte != '\n') { getOption().append((char) currentByte); currentByte = getc(is); } if (currentByte != ':' && currentByte != '=') { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "''{0}'' : ''{1}'' : Option must end with ':' or '='.", new Object[]{getConfigPath(), new Integer(getCurrentLineNumber())}), SVNLogType.NETWORK); } else { trimBuffer(getOption()); currentByte = parseValue(is); } return currentByte; } private int parseValue(InputStream is) throws IOException, SVNException { getValue().setLength(0); int currentByte = getc(is); boolean isEndOfValue = false; while (currentByte != -1 && currentByte != '\n') { getValue().append((char) currentByte); currentByte = getc(is); } trimBuffer(getValue()); while (true) { if (currentByte == -1 || isEndOfValue) { updateConfiguration(); break; } increaseCurrentLineNumber(); currentByte = skipWhitespace(is); switch (currentByte) { case'\n': increaseCurrentLineNumber(); isEndOfValue = true; continue; case-1: isEndOfValue = true; continue; default: if (getCurrentLineColumn() == 0) { ungetc((char) currentByte); isEndOfValue = true; } else { //Continuation line found. getValue().append(' '); while (currentByte != -1 && currentByte != '\n') { getValue().append((char) currentByte); currentByte = getc(is); } trimBuffer(getValue()); } } } return currentByte; } private int skipWhitespace(InputStream is) throws IOException { resetCurrentLineColumn(); int currentByte = getc(is); while (Character.isWhitespace((char) currentByte)) { currentByte = getc(is); increaseCurrentLineColumn(); } return currentByte; } private int skipToEndOfLine(InputStream is) throws IOException { int currentByte = getc(is); while (currentByte != -1 && currentByte != '\n') { currentByte = getc(is); resetCurrentLineColumn(); } return currentByte; } private int getc(InputStream is) throws IOException { if (hasUngottenChar()) { setHasUngottenChar(false); return getUngottenChar(); } return is.read(); } private void ungetc(char ungottenChar) { setUngottenChar(ungottenChar); setHasUngottenChar(true); } private void trimBuffer(StringBuffer buffer) { while (buffer.length() > 0 && Character.isWhitespace(buffer.charAt(0))) { buffer.deleteCharAt(0); } while (buffer.length() > 0 && Character.isWhitespace(buffer.charAt(buffer.length() - 1))) { buffer.deleteCharAt(buffer.length() - 1); } } private void updateConfiguration() throws SVNException { if ("groups".equals(getSectionName().toString())) { updateGroups(); } else if ("aliases".equals(getSectionName().toString())) { updateAliases(); } else { updateRules(); } } private void updateGroups() throws SVNException { String groupName = getOption().toString(); if (getValue().length() == 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "An authz rule refers to group ''{0}'', which is undefined", groupName), SVNLogType.NETWORK); } String[] users = COMMA.split(getValue()); getGroups().put(groupName, users); } private void updateAliases() throws SVNException { String alias = getOption().toString(); if (getValue().length() == 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "An authz rule refers to alies ''{0}'', which is undefined", alias), SVNLogType.NETWORK); } getAliases().put(alias, getValue().toString()); } private void updateRules() throws SVNException { int delimeterIndex = getSectionName().indexOf(":"); String repositoryName = delimeterIndex == -1 ? ANONYMOUS_REPOSITORY : getSectionName().substring(0, delimeterIndex); String path = delimeterIndex == -1 ? getSectionName().toString() : getSectionName().substring(delimeterIndex + 1); String value = getValue().toString(); if (getOption().charAt(0) == '~') { if (getOption().charAt(1) == '~') { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "Rule ''{0}'' has more than one inversion; double negatives are not permitted.", getOption()), SVNLogType.NETWORK); } if (getOption().charAt(1) == '*') { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "Authz rules with match string '~*' are not allowed, because they never match anyone."), SVNLogType.NETWORK); } } if (getOption().charAt(0) == '$') { String token = getOption().substring(1); if (!"anonymous".equals(token) && !"authenticated".equals(token)) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "Unrecognized authz token ''{0}''.", getOption()), SVNLogType.NETWORK); } } if (value.length() > 0 && !"r".equals(value) && !"rw".equals(value)) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "The value ''{0}'' in rule ''{1}'' is not allowed in authz rules.", new Object[]{value, getOption()}), SVNLogType.NETWORK); } RepositoryAccess repositoryAccess = (RepositoryAccess) getRules().get(repositoryName); if (repositoryAccess == null) { repositoryAccess = new RepositoryAccess(ANONYMOUS_REPOSITORY.equals(repositoryName)); getRules().put(repositoryName, repositoryAccess); } repositoryAccess.addRule(path, getOption().toString(), getValue().toString()); } private void validate() throws SVNException { Collection checkedPathes = new ArrayList(); for (Iterator iterator = getGroups().keySet().iterator(); iterator.hasNext();) { String groupName = (String) iterator.next(); checkedPathes.clear(); groupWalk(groupName, checkedPathes); } for (Iterator repositories = getRules().values().iterator(); repositories.hasNext();) { RepositoryAccess repositoryAccess = (RepositoryAccess) repositories.next(); repositoryAccess.validateRules(); } } private void groupWalk(String group, Collection checkedGroups) throws SVNException { String[] users = (String[]) getGroups().get(group); if (users == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "An authz rule refers to group ''{0}'', which is undefined.", group), SVNLogType.NETWORK); } for (int i = 0; i < users.length; i++) { users[i] = users[i].trim(); if (users[i].startsWith("@")) { String subGroup = users[i].substring("@".length()); if (checkedGroups.contains(subGroup)) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "Circular dependency between groups ''{0}'' and ''{1}''", new Object[]{group, subGroup}), SVNLogType.NETWORK); } checkedGroups.add(subGroup); groupWalk(subGroup, checkedGroups); checkedGroups.remove(subGroup); } else if (users[i].startsWith("&")) { String alias = users[i].substring("&".length()); if (!getAliases().keySet().contains(alias)) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "An authz rule refers to alias ''{0}'', which is undefined.", alias), SVNLogType.NETWORK); } } } } private class RepositoryAccess { boolean myAnonymous = false; private Map myPathRules; private PathAccess myGlobalAccess; private RepositoryAccess(boolean isAnonymous) { myAnonymous = isAnonymous; } private void addRule(String path, String matchString, String value) { if (path.equals("/") || path.length() == 0) { myGlobalAccess = myGlobalAccess == null ? new PathAccess() : myGlobalAccess; myGlobalAccess.addRule(matchString, value); } myPathRules = myPathRules == null ? new SVNHashMap() : myPathRules; PathAccess pathAccess = (PathAccess) myPathRules.get(path); if (pathAccess == null) { pathAccess = new PathAccess(); myPathRules.put(path, pathAccess); } pathAccess.addRule(matchString, value); } private void validateRules() throws SVNException { if (myGlobalAccess != null) { myGlobalAccess.validateRules(); } if (myPathRules != null) { for (Iterator iterator = myPathRules.values().iterator(); iterator.hasNext();) { PathAccess pathAccess = (PathAccess) iterator.next(); pathAccess.validateRules(); } } } private boolean checkPathAccess(String path, String user, int requestedAccess) { boolean accessGranted = false; if (path == null || path.length() == 0 || "/".equals(path)) { if (myGlobalAccess != null) { int[] pathAccess = myGlobalAccess.checkAccess(user); if (isAccessDetermined(pathAccess, requestedAccess)) { accessGranted = isAccessGranted(pathAccess, requestedAccess); } } } else { if (myPathRules == null) { return false; } int[] pathAccess = checkCurrentPath(path, user); if (isAccessDetermined(pathAccess, requestedAccess)) { accessGranted = isAccessGranted(pathAccess, requestedAccess); } else { String currentPath = path; while (currentPath.length() > 0 && !"/".equals(currentPath)) { currentPath = SVNPathUtil.getAbsolutePath(SVNPathUtil.removeTail(currentPath)); pathAccess = checkCurrentPath(currentPath, user); if (isAccessDetermined(pathAccess, requestedAccess)) { accessGranted = isAccessGranted(pathAccess, requestedAccess); break; } } } } if (accessGranted && ((requestedAccess & SVN_ACCESS_RECURSIVE) != SVN_ACCESS_NONE)) { accessGranted = checkTreeAccess(user, path, requestedAccess); } return accessGranted; } private int[] checkCurrentPath(String currentPath, String user) { int[] pathAccess = new int[]{SVN_ACCESS_NONE, SVN_ACCESS_NONE}; PathAccess currentPathAccess = (PathAccess) myPathRules.get(currentPath); if (currentPathAccess != null) { pathAccess = currentPathAccess.checkAccess(user); } else if (!myAnonymous) { RepositoryAccess commonRepositoryAccess = (RepositoryAccess) getRules().get(ANONYMOUS_REPOSITORY); if (commonRepositoryAccess != null) { pathAccess = commonRepositoryAccess.checkPathAccess(user, currentPath); } } return pathAccess; } private int[] checkPathAccess(String user, String path) { int[] result = new int[]{SVN_ACCESS_NONE, SVN_ACCESS_NONE}; PathAccess pathAccess = (PathAccess) myPathRules.get(path); if (pathAccess != null) { result = pathAccess.checkAccess(user); } return result; } private boolean checkTreeAccess(String user, String path, int requestedAccess) { if (myRules == null) { return false; } boolean accessGranted = true; for (Iterator iterator = myRules.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String currentPath = (String) entry.getKey(); if (SVNPathUtil.isAncestor(path, currentPath)) { PathAccess currentPathAccess = (PathAccess) entry.getValue(); int[] pathAccess = currentPathAccess.checkAccess(user); accessGranted = isAccessGranted(pathAccess, requestedAccess) || !isAccessDetermined(pathAccess, requestedAccess); if (!accessGranted) { return accessGranted; } } } return accessGranted; } private boolean isAccessGranted(int[] pathAccess, int requestedAccess) { if (pathAccess == null) { return false; } int allow = pathAccess[0]; int deny = pathAccess[1]; int strippedAccess = requestedAccess & (SVN_ACCESS_READ | SVN_ACCESS_WRITE); return (deny & requestedAccess) == SVN_ACCESS_NONE || (allow & requestedAccess) == strippedAccess; } private boolean isAccessDetermined(int[] pathAccess, int requestedAccess) { if (pathAccess == null) { return false; } int allow = pathAccess[0]; int deny = pathAccess[1]; return ((deny & requestedAccess) != SVN_ACCESS_NONE) || ((allow & requestedAccess) != SVN_ACCESS_NONE); } } private class PathAccess { private Map myRules; private void addRule(String matchString, String value) { myRules = myRules == null ? new SVNHashMap() : myRules; myRules.put(matchString, value); } private void validateRules() throws SVNException { if (myRules != null) { for (Iterator iterator = myRules.keySet().iterator(); iterator.hasNext();) { String matchString = (String) iterator.next(); if (matchString.startsWith("@")) { if (!getGroups().keySet().contains(matchString.substring("@".length()))) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "An authz rule refers to group ''{0}'', which is undefined.", matchString), SVNLogType.NETWORK); } } else if (matchString.startsWith("&")) { if (!getAliases().keySet().contains(matchString.substring("&".length()))) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_INVALID_CONFIG_VALUE, "An authz rule refers to alias ''{0}'', which is undefined.", matchString), SVNLogType.NETWORK); } } } } } private int[] checkAccess(String user) { if (myRules == null) { return null; } int deny = SVN_ACCESS_NONE; int allow = SVN_ACCESS_NONE; for (Iterator iterator = myRules.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String matchString = (String) entry.getKey(); String accessType = (String) entry.getValue(); if (ruleApliesToUser(matchString, user)) { if (accessType.indexOf('r') >= 0) { allow |= SVN_ACCESS_READ; } else { deny |= SVN_ACCESS_READ; } if (accessType.indexOf('w') >= 0) { allow |= SVN_ACCESS_WRITE; } else { deny |= SVN_ACCESS_WRITE; } } } return new int[]{allow, deny}; } private boolean ruleApliesToUser(String matchString, String user) { if (matchString.startsWith("~")) { return !ruleApliesToUser(matchString.substring("~".length()), user); } if (matchString.equals("*")) { return true; } if (matchString.equals("$anonymous")) { return user == null; } if (matchString.equals("$authenticated")) { return user != null; } if (user == null) { return false; } if (matchString.startsWith("@")) { return groupContainsUser(matchString.substring("@".length()), user); } else if (matchString.startsWith("&")) { return aliasIsUser(matchString.substring("&".length()), user); } else { return matchString.equals(user); } } } }svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/000077500000000000000000000000001177510526000325365ustar00rootroot00000000000000DAVBase64OutputStream.java000066400000000000000000000041561177510526000373040ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.tmatesoft.svn.core.internal.util.SVNBase64; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVBase64OutputStream extends OutputStream { private static final int BASE64_LINE_LENGTH = 57; private Writer myWriter; private ByteArrayOutputStream myBuffer; public DAVBase64OutputStream(Writer dst) { myWriter = dst; myBuffer = new ByteArrayOutputStream(100); } public void write(int b) throws IOException { write(new byte[] {(byte) (b & 0xff)}, 0, 1); } public void write(byte[] b) throws IOException { write(b, 0, b.length); } public void close() throws IOException { flush(); } public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { int needed = BASE64_LINE_LENGTH - myBuffer.size(); int toWrite = Math.min(needed, len); myBuffer.write(b, off, toWrite); off += toWrite; len -= toWrite; if (myBuffer.size() == BASE64_LINE_LENGTH) { flushBuffer(); } } } public void flush() throws IOException { if (myBuffer.size() > 0) { flushBuffer(); } } private void flushBuffer() throws IOException { myWriter.write(SVNBase64.byteArrayToBase64(myBuffer.toByteArray()) + "\n"); myBuffer.reset(); } } DAVCheckOutHandler.java000066400000000000000000000140771177510526000366710ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPHeader; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVCheckOutHandler extends ServletDAVHandler { private DAVCheckOutRequest myDAVRequest; public DAVCheckOutHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } public void execute() throws SVNException { long readLength = readInput(false); boolean applyToVSN = false; boolean isUnreserved = false; boolean createActivity = false; List activities = null; if (readLength > 0) { DAVCheckOutRequest davRequest = getCheckOutRequest(); if (davRequest.isApplyToVersion()) { if (getRequestHeader(LABEL_HEADER) != null) { response("DAV:apply-to-version cannot be used in conjunction with a Label header.", DAVServlet.getStatusLine(HttpServletResponse.SC_CONFLICT), HttpServletResponse.SC_CONFLICT); } applyToVSN = true; } isUnreserved = davRequest.isUnreserved(); DAVElementProperty rootElement = davRequest.getRoot(); DAVElementProperty activitySetElement = rootElement.getChild(DAVCheckOutRequest.ACTIVITY_SET); if (activitySetElement != null) { if (activitySetElement.hasChild(DAVCheckOutRequest.NEW)) { createActivity = true; } else { activities = new LinkedList(); List activitySetChildren = activitySetElement.getChildren(); for (Iterator activitySetIter = activitySetChildren.iterator(); activitySetIter.hasNext();) { DAVElementProperty activitySetChild = (DAVElementProperty) activitySetIter.next(); if (activitySetChild.getName() == DAVElement.HREF) { activities.add(activitySetChild.getFirstValue(true)); } } if (activities.isEmpty()) { throw new DAVException("Within the DAV:activity-set element, the DAV:new element must be used, or at least one DAV:href must be specified.", null, HttpServletResponse.SC_BAD_REQUEST, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } } } } DAVResource resource = getRequestedDAVResource(true, applyToVSN); if (!resource.exists()) { throw new DAVException(DAVServlet.getStatusLine(HttpServletResponse.SC_NOT_FOUND), null, HttpServletResponse.SC_NOT_FOUND, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } if (resource.getResourceURI().getType() != DAVResourceType.REGULAR && resource.getResourceURI().getType() != DAVResourceType.VERSION) { response("Cannot checkout this type of resource.", DAVServlet.getStatusLine(HttpServletResponse.SC_CONFLICT), HttpServletResponse.SC_CONFLICT); } if (!resource.isVersioned()) { response("Cannot checkout unversioned resource.", DAVServlet.getStatusLine(HttpServletResponse.SC_CONFLICT), HttpServletResponse.SC_CONFLICT); } if (resource.isWorking()) { response("The resource is already checked out to the workspace.", DAVServlet.getStatusLine(HttpServletResponse.SC_CONFLICT), HttpServletResponse.SC_CONFLICT); } DAVResource workingResource = null; try { workingResource = checkOut(resource, false, isUnreserved, createActivity, activities); } catch (DAVException dave) { throw new DAVException("Could not CHECKOUT resource {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } setResponseHeader(CACHE_CONTROL_HEADER, CACHE_CONTROL_VALUE); if (workingResource == null) { setResponseHeader(HTTPHeader.CONTENT_LENGTH_HEADER, "0"); return; } handleDAVCreated(workingResource.getResourceURI().getRequestURI(), "Checked-out resource", false); } protected DAVRequest getDAVRequest() { return getCheckOutRequest(); } private DAVCheckOutRequest getCheckOutRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVCheckOutRequest(); } return myDAVRequest; } } DAVCheckOutRequest.java000066400000000000000000000053671177510526000367460ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVCheckOutRequest extends DAVRequest { public static final DAVElement NEW = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "new"); public static final DAVElement CHECKOUT = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "checkout"); public static final DAVElement APPLY_TO_VERSION = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "apply-to-version"); public static final DAVElement UNRESERVED = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "unreserved"); public static final DAVElement FORK_OK = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "fork-ok"); public static final DAVElement ACTIVITY_SET = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "activity-set"); public boolean isUnreserved() throws SVNException { DAVElementProperty root = getRoot(); return root.hasChild(UNRESERVED); } public boolean isForkOk() throws SVNException { DAVElementProperty root = getRoot(); return root.hasChild(FORK_OK); } public boolean isApplyToVersion() throws SVNException { DAVElementProperty root = getRoot(); return root.hasChild(APPLY_TO_VERSION); } public DAVElementProperty getRoot() throws SVNException { if (getRootElement() == null) { invalidXMLRoot(); } return getRootElement(); } protected void init() throws SVNException { DAVElementProperty rootElement = getRootElement(); if (rootElement == null || rootElement.getName() != CHECKOUT) { invalidXMLRoot(); } } protected void invalidXMLRoot() throws SVNException { throw new DAVException("The request body, if present, must be a DAV:checkout element.", null, HttpServletResponse.SC_BAD_REQUEST, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } } DAVCopyMoveHandler.java000066400000000000000000000277141177510526000367270ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.net.URI; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPHeader; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceState; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; import org.tmatesoft.svn.core.internal.server.dav.DAVServletUtil; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVCopyMoveHandler extends ServletDAVHandler { private boolean myIsMove; protected DAVCopyMoveHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response, boolean isMove) { super(connector, request, response); myIsMove = isMove; } public void execute() throws SVNException { DAVResource resource = getRequestedDAVResource(!myIsMove, false); if (!resource.exists()) { sendError(HttpServletResponse.SC_NOT_FOUND, null); return; } if (resource.getType() != DAVResourceType.REGULAR) { String body = "Cannot COPY/MOVE resource " + SVNEncodingUtil.xmlEncodeCDATA(getURI()) + "."; response(body, DAVServlet.getStatusLine(HttpServletResponse.SC_METHOD_NOT_ALLOWED), HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } String destination = getRequestHeader(HTTPHeader.DESTINATION_HEADER); if (destination == null) { String netScapeHost = getRequestHeader(HTTPHeader.HOST_HEADER); String netScapeNewURI = getRequestHeader(HTTPHeader.NEW_URI_HEADER); if (netScapeHost != null && netScapeNewURI != null) { String path = SVNPathUtil.append(netScapeHost, netScapeNewURI); if (path.startsWith("/")) { path = path.substring(1); } destination = "http://" + path; } } if (destination == null) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "The request is missing a Destination header."); sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } URI uri = null; try { uri = DAVServletUtil.lookUpURI(destination, getRequest(), true); } catch (DAVException dave) { if (dave.getResponseCode() == HttpServletResponse.SC_BAD_REQUEST) { throw dave; } response(dave.getMessage(), DAVServlet.getStatusLine(dave.getResponseCode()), dave.getResponseCode()); } String path = uri.getPath(); DAVRepositoryManager manager = getRepositoryManager(); String resourceContext = manager.getResourceContext(); if (!path.startsWith(resourceContext)) { throw new DAVException("Destination url starts with a wrong context", HttpServletResponse.SC_BAD_REQUEST, 0); } path = path.substring(resourceContext.length()); DAVResource newResource = getRequestedDAVResource(false, false, path); int overwrite = getOverwrite(); if (overwrite < 0) { sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } if (newResource.exists() && overwrite == 0) { response("Destination is not empty and Overwrite is not \"T\"", DAVServlet.getStatusLine(HttpServletResponse.SC_PRECONDITION_FAILED), HttpServletResponse.SC_PRECONDITION_FAILED); return; } if (resource.equals(newResource)) { response("Source and Destination URIs are the same.", DAVServlet.getStatusLine(HttpServletResponse.SC_FORBIDDEN), HttpServletResponse.SC_FORBIDDEN); return; } boolean isDir = resource.isCollection(); DAVDepth depth = null; try { depth = getRequestDepth(DAVDepth.DEPTH_INFINITY); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_BAD_REQUEST, null, null); } if (depth == DAVDepth.DEPTH_ONE) { //add logging here later sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } if (myIsMove && isDir && depth != DAVDepth.DEPTH_INFINITY) { //add logging here later sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } if (myIsMove) { try { validateRequest(resource, depth, DAV_VALIDATE_PARENT | DAV_VALIDATE_USE_424, null, null, null); } catch (DAVException dave) { throw new DAVException("Could not MOVE {0} due to a failed precondition on the source (e.g. locks).", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, dave.getResponseCode(), null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, dave.getResponse()); } } try { validateRequest(newResource, DAVDepth.DEPTH_INFINITY, DAV_VALIDATE_PARENT | DAV_VALIDATE_USE_424, null, null, null); } catch (DAVException dave) { throw new DAVException("Could not MOVE/COPY {0} due to a failed precondition on the destination (e.g. locks).", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, dave.getResponseCode(), null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, dave.getResponse()); } if (isDir && depth == DAVDepth.DEPTH_INFINITY && resource.isParentResource(newResource)) { response("Source collection contains the Destination.", DAVServlet.getStatusLine(HttpServletResponse.SC_FORBIDDEN), HttpServletResponse.SC_FORBIDDEN); return; } if (isDir && newResource.isParentResource(newResource)) { response("Destination collection contains the Source and Overwrite has been specified.", DAVServlet.getStatusLine(HttpServletResponse.SC_FORBIDDEN), HttpServletResponse.SC_FORBIDDEN); return; } readInput(true); DAVLockInfoProvider lockProvider = null; try { lockProvider = DAVLockInfoProvider.createLockInfoProvider(this, false); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, null); } if (myIsMove) { unlock(resource, null); } DAVAutoVersionInfo srcAVInfo = null; if (myIsMove) { srcAVInfo = autoCheckOut(resource, true); } boolean replaceDestination = false; DAVResourceState resNewState = getResourceState(newResource); if (newResource.exists()) { if (myIsMove || !newResource.isVersioned()) { replaceDestination = true; } else if (resource.getType() != newResource.getType()) { replaceDestination = true; } else if (resource.isCollection() != newResource.isCollection()) { replaceDestination = true; } } DAVAutoVersionInfo dstAVInfo = null; if (!newResource.exists() || replaceDestination) { try { dstAVInfo = autoCheckOut(newResource, true); } catch (DAVException dave) { if (myIsMove) { autoCheckIn(null, true, false, srcAVInfo); } throw dave; } } if (srcAVInfo != null && srcAVInfo.getParentResource() != null && dstAVInfo != null && dstAVInfo.getParentResource() != null) { DAVResource srcParentResource = srcAVInfo.getParentResource(); DAVResource dstParentResource = dstAVInfo.getParentResource(); if (srcParentResource.equals(dstParentResource)) { dstAVInfo.setParentResource(srcAVInfo.getParentResource()); } } DAVException err1 = null; if (replaceDestination) { try { removeResource(newResource); } catch (DAVException dave) { err1 = dave; } } if (err1 == null) { if (myIsMove) { try { moveResource(resource, newResource); } catch (DAVException dave) { err1 = dave; } } else { try { copyResource(resource, newResource); } catch (DAVException dave) { err1 = dave; } } } DAVException err2 = null; try { autoCheckIn(null, err1 != null, false, dstAVInfo); } catch (DAVException dave) { err2 = dave; } DAVException err3 = null; if (myIsMove) { try { autoCheckIn(null, err1 != null, false, srcAVInfo); } catch (DAVException dave) { err3 = dave; } } if (err1 != null) { throw new DAVException("Could not MOVE/COPY {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, err1.getResponseCode(), err1, 0); } if (err2 != null) { //throw new DAVException("The MOVE/COPY was successful, but there was a problem automatically checking in the source parent collection.", null, err2.getResponseCode(), err2, 0); //TODO: add logging here later } if (err3 != null) { //TODO: add logging here later } try { notifyCreated(newResource, lockProvider, resNewState, depth); } catch (DAVException dave) { throw new DAVException("The MOVE/COPY was successful, but there was a problem updating the lock information.", null, dave.getResponseCode(), dave, 0); } handleDAVCreated(uri.toString(), "Destination", resNewState == DAVResourceState.EXISTS); } protected int getOverwrite() { String overwriteValue = getRequestHeader(HTTPHeader.OVERWRITE_HEADER); if (overwriteValue == null) { return 1; } overwriteValue = overwriteValue.toLowerCase(); if (overwriteValue.length() == 1 && overwriteValue.charAt(0) == 'f') { return 0; } if (overwriteValue.length() == 1 && overwriteValue.charAt(0) == 't') { return 1; } //TODO: add logging here later return -1; } protected DAVRequest getDAVRequest() { return null; } } DAVDatedRevisionHandler.java000066400000000000000000000051011177510526000377100ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVDatedRevisionHandler extends DAVReportHandler { private DAVDatedRevisionRequest myDAVRequest; public DAVDatedRevisionHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } protected DAVRequest getDAVRequest() { return getDatedRevisionRequest(); } private DAVDatedRevisionRequest getDatedRevisionRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVDatedRevisionRequest(); } return myDAVRequest; } public void execute() throws SVNException { setDAVResource(getRequestedDAVResource(false, false)); String responseBody = generateResponseBody(); try { int contentLength = responseBody.getBytes(UTF8_ENCODING).length; setResponseContentLength(contentLength); } catch (UnsupportedEncodingException e) { } write(responseBody); } private String generateResponseBody() throws SVNException { StringBuffer xmlBuffer = new StringBuffer(); long revision = getDatedRevision(); addXMLHeader(xmlBuffer, null); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.VERSION_NAME.getName(), String.valueOf(revision), xmlBuffer); addXMLFooter(xmlBuffer, null); return xmlBuffer.toString(); } private long getDatedRevision() throws SVNException { return getDAVResource().getRepository().getDatedRevision(getDatedRevisionRequest().getDate()); } } DAVDatedRevisionRequest.java000066400000000000000000000024411177510526000377670ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Date; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.util.SVNDate; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVDatedRevisionRequest extends DAVRequest { Date myDate = null; public Date getDate() { return myDate; } private void setDate(Date date) { myDate = date; } protected void init() throws SVNException { DAVElementProperty creationDateElement = getRootElement().getChild(DAVElement.CREATION_DATE); String dateString = creationDateElement.getFirstValue(true); setDate(SVNDate.parseDate(dateString)); } } DAVDeleteHandler.java000066400000000000000000000100311177510526000363500ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVDeleteHandler extends ServletDAVHandler { private DAVDeleteRequest myDAVRequest; public DAVDeleteHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } public void execute() throws SVNException { readInput(false); DAVResource resource = getRequestedDAVResource(false, false); if (!resource.exists()) { sendError(HttpServletResponse.SC_NOT_FOUND, null); return; } DAVDepth depth = getRequestDepth(DAVDepth.DEPTH_INFINITY); if (resource.isCollection() && depth != DAVDepth.DEPTH_INFINITY) { SVNDebugLog.getDefaultLog().logError(SVNLogType.NETWORK, "Depth must be \"infinity\" for DELETE of a collection."); sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } if (!resource.isCollection() && depth == DAVDepth.DEPTH_ONE) { SVNDebugLog.getDefaultLog().logError(SVNLogType.NETWORK, "Depth of \"1\" is not allowed for DELETE."); sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } try { validateRequest(resource, depth, DAV_VALIDATE_PARENT | DAV_VALIDATE_USE_424, null, null, null); } catch (DAVException dave) { throw new DAVException("Could not DELETE {0} due to a failed precondition (e.g. locks).", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, dave.getResponseCode(), null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, dave.getResponse()); } int respCode = unlock(resource, null); if (respCode != HttpServletResponse.SC_OK) { sendError(respCode, null); return; } DAVAutoVersionInfo avInfo = autoCheckOut(resource, true); try { removeResource(resource); } catch (DAVException dave) { autoCheckIn(null, true, false, avInfo); throw new DAVException("Could not DELETE {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, dave.getResponseCode(), dave, 0); } try { autoCheckIn(null, false, false, avInfo); } catch (DAVException dave) { //TODO: add better logging here later SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "The DELETE was successful, but there was a problem automatically checking in the parent collection."); } setResponseStatus(HttpServletResponse.SC_NO_CONTENT); } protected DAVRequest getDAVRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVDeleteRequest(); } return myDAVRequest; } } DAVDeleteRequest.java000066400000000000000000000014441177510526000364330ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import org.tmatesoft.svn.core.SVNException; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVDeleteRequest extends DAVRequest { protected void init() throws SVNException { } } DAVElementProperty.java000066400000000000000000000107241177510526000370170ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.Attributes; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVElementProperty { private ArrayList myValues; private Map myAttributes; private List myChildren; private DAVElement myElementName; private DAVElementProperty myParent; private LivePropertySpecification myLivePropertySpec; public DAVElementProperty(DAVElement elementName, DAVElementProperty parent) { myElementName = elementName; myParent = parent; } public DAVElementProperty getParent() { return myParent; } public DAVElement getName() { return myElementName; } public void setElementName(DAVElement element) { myElementName = element; } public boolean hasChild(DAVElement element) { return getChild(element) != null; } public DAVElementProperty getChild(DAVElement element) { if (myChildren != null) { for (Iterator childrenIter = myChildren.iterator(); childrenIter.hasNext();) { DAVElementProperty nextChild = (DAVElementProperty) childrenIter.next(); if (element == nextChild.getName()) { return nextChild; } } } return null; } public Map getAttributes() { return myAttributes; } public void addValue(String cdata) throws SVNException { if (myChildren != null) { invalidXML(); } else if (myValues == null) { myValues = new ArrayList(); } myValues.add(cdata); } public String getFirstValue(boolean trim) { if (myValues != null) { String value = (String) myValues.get(0); if (trim && value != null) { value = value.trim(); } return value; } return null; } public Collection getValues() { return myValues; } public String getAttributeValue(String name) { if (myAttributes != null) { return (String) myAttributes.get(name); } return null; } public void setAttributes(Attributes attributes) { myAttributes = getAttributesMap(attributes); } public List getChildren() { return myChildren; } public boolean isEmpty() { return (myChildren == null || myChildren.isEmpty()) && (myValues == null || myValues.isEmpty()); } protected DAVElementProperty addChild(DAVElement element, Attributes attrs) throws SVNException { if (myValues != null) { invalidXML(); } else if (myChildren == null) { myChildren = new LinkedList(); } DAVElementProperty child = new DAVElementProperty(element, this); myChildren.add(child); child.setAttributes(attrs); return child; } private Map getAttributesMap(Attributes attrs) { Map attributes = null; if (attrs.getLength() != 0) { attributes = new SVNHashMap(); for (int i = 0; i < attrs.getLength(); i++) { attributes.put(attrs.getLocalName(i), attrs.getValue(i)); } } return attributes; } private void invalidXML() throws SVNException { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.XML_MALFORMED, "Malformed XML"), SVNLogType.NETWORK); } } DAVFileRevisionsHandler.java000066400000000000000000000151341177510526000377400ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.OutputStream; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.io.ISVNFileRevisionHandler; import org.tmatesoft.svn.core.io.SVNFileRevision; import org.tmatesoft.svn.core.io.diff.SVNDiffWindow; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVFileRevisionsHandler extends DAVReportHandler implements ISVNFileRevisionHandler { private static final String FILE_REVISION_TAG = "file-rev"; private static final String REVISION_PROPERTY_TAG = "rev-prop"; private static final String SET_PROPERTY_TAG = "set-prop"; private static final String REMOVE_PROPERTY_TAG = "remove-prop"; private static final String MERGED_REVISION_TAG = "merged-revision"; private DAVFileRevisionsRequest myDAVRequest; private boolean myWriteHeader; private DAVReportHandler myCommonReportHandler; public DAVFileRevisionsHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(repositoryManager, request, response); myCommonReportHandler = commonReportHandler; } protected DAVRequest getDAVRequest() { return getFileRevsionsRequest(); } private DAVFileRevisionsRequest getFileRevsionsRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVFileRevisionsRequest(); } return myDAVRequest; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace(null); setDAVResource(getRequestedDAVResource(false, false)); myWriteHeader = true; String path = SVNPathUtil.append(getDAVResource().getResourceURI().getPath(), getFileRevsionsRequest().getPath()); try { getDAVResource().getRepository().getFileRevisions(path, getFileRevsionsRequest().getStartRevision(), getFileRevsionsRequest().getEndRevision(), getFileRevsionsRequest().isIncludeMergedRevisions(), this); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, svne.getErrorMessage().getMessage(), null); } try { maybeSendHeader(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error beginning REPORT reponse", null); } try { writeXMLFooter(null); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error ending REPORT reponse", null); } } public void openRevision(SVNFileRevision fileRevision) throws SVNException { maybeSendHeader(); Map attrs = new SVNHashMap(); attrs.put(PATH_ATTR, fileRevision.getPath()); attrs.put(REVISION_ATTR, String.valueOf(fileRevision.getRevision())); StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, FILE_REVISION_TAG, SVNXMLUtil.XML_STYLE_NORMAL, attrs, null); write(xmlBuffer); for (Iterator iterator = fileRevision.getRevisionProperties().nameSet().iterator(); iterator.hasNext();) { String propertyName = (String) iterator.next(); writePropertyTag(REVISION_PROPERTY_TAG, propertyName, fileRevision.getRevisionProperties().getSVNPropertyValue(propertyName)); } for (Iterator iterator = fileRevision.getPropertiesDelta().nameSet().iterator(); iterator.hasNext();) { String propertyName = (String) iterator.next(); SVNPropertyValue propertyValue = fileRevision.getPropertiesDelta().getSVNPropertyValue(propertyName); if (propertyValue != null) { writePropertyTag(SET_PROPERTY_TAG, propertyName, propertyValue); } else { xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, REMOVE_PROPERTY_TAG, SVNXMLUtil.XML_STYLE_SELF_CLOSING, "name", propertyName, null); write(xmlBuffer); } } if (fileRevision.isResultOfMerge()) { xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, MERGED_REVISION_TAG, SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, null); write(xmlBuffer); } } public void closeRevision(String token) throws SVNException { StringBuffer xmlBuffer = SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, FILE_REVISION_TAG, null); write(xmlBuffer); } public void applyTextDelta(String path, String baseChecksum) throws SVNException { StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, TXDELTA_ATTR, SVNXMLUtil.XML_STYLE_NORMAL, null, null); write(xmlBuffer); } public OutputStream textDeltaChunk(String path, SVNDiffWindow diffWindow) throws SVNException { writeTextDeltaChunk(diffWindow); return null; } public void textDeltaEnd(String path) throws SVNException { textDeltaChunkEnd(); setWriteTextDeltaHeader(true); StringBuffer xmlBuffer = SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, TXDELTA_ATTR, null); write(xmlBuffer); } private void maybeSendHeader() throws SVNException { if (myWriteHeader) { writeXMLHeader(null); myWriteHeader = false; } } } DAVFileRevisionsRequest.java000066400000000000000000000064041177510526000400130ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVFileRevisionsRequest extends DAVRequest { private String myPath; private long myStartRevision = DAVResource.INVALID_REVISION; private long myEndRevision = DAVResource.INVALID_REVISION; private boolean myIsIncludeMergedRevisions; public String getPath() { return myPath; } public long getStartRevision() { return myStartRevision; } public long getEndRevision() { return myEndRevision; } public boolean isIncludeMergedRevisions() { return myIsIncludeMergedRevisions; } protected void init() throws SVNException { DAVElementProperty rootElement = getRootElement(); List children = rootElement.getChildren(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { DAVElementProperty childElement = (DAVElementProperty) iterator.next(); DAVElement childElementName = childElement.getName(); if (!DAVElement.SVN_NAMESPACE.equals(childElementName.getNamespace())) { continue; } if (childElementName == DAVElement.PATH) { String path = childElement.getFirstValue(false); DAVPathUtil.testCanonical(path); myPath = path; } else if (childElementName == DAVElement.START_REVISION) { try { myStartRevision = Long.parseLong(childElement.getFirstValue(true)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (childElementName == DAVElement.END_REVISION) { try { myEndRevision = Long.parseLong(childElement.getFirstValue(true)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (childElementName == DAVElement.INCLUDE_MERGED_REVISIONS) { myIsIncludeMergedRevisions = true; } } } } DAVGetDeletedRevisionHandler.java000066400000000000000000000074221177510526000407050ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceURI; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVGetDeletedRevisionHandler extends DAVReportHandler { private DAVGetDeletedRevisionRequest myDAVRequest; private DAVReportHandler myCommonReportHandler; protected DAVGetDeletedRevisionHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(connector, request, response); myCommonReportHandler = commonReportHandler; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace(null); setDAVResource(getRequestedDAVResource(false, false)); DAVGetDeletedRevisionRequest request = getDeletedRevisionRequest(); String relPath = request.getPath(); long pegRev = request.getPegRevision(); long endRev = request.getEndRevision(); if (relPath == null || !SVNRevision.isValidRevisionNumber(pegRev) || !SVNRevision.isValidRevisionNumber(endRev)) { throw new DAVException("Not all parameters passed.", null, HttpServletResponse.SC_BAD_REQUEST, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, 0, null); } DAVResourceURI resourceURI = getDAVResource().getResourceURI(); String path = relPath; if (!path.startsWith("/")) { path = SVNPathUtil.append(resourceURI.getPath(), relPath); } SVNRepository repository = getDAVResource().getRepository(); long deletedRev = SVNRepository.INVALID_REVISION; try { deletedRev = repository.getDeletedRevision(path, pegRev, endRev); } catch (SVNException svne) { throw new DAVException("Could not find revision path was deleted.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } writeXMLHeader(null); StringBuffer xmlBuffer = SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.VERSION_NAME.getName(), String.valueOf(deletedRev), null); write(xmlBuffer); writeXMLFooter(null); } protected DAVRequest getDAVRequest() { return getDeletedRevisionRequest(); } private DAVGetDeletedRevisionRequest getDeletedRevisionRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVGetDeletedRevisionRequest(); } return myDAVRequest; } } DAVGetDeletedRevisionRequest.java000066400000000000000000000060411177510526000407540ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVGetDeletedRevisionRequest extends DAVRequest { private long myPegRevision; private long myEndRevision; private String myPath; public long getPegRevision() { return myPegRevision; } public long getEndRevision() { return myEndRevision; } public String getPath() { return myPath; } protected void init() throws SVNException { DAVElementProperty rootElement = getRootElement(); List rootChildren = rootElement.getChildren(); if (rootChildren != null) { for (Iterator childrenIter = rootChildren.iterator(); childrenIter.hasNext();) { DAVElementProperty childElement = (DAVElementProperty) childrenIter.next(); DAVElement childElementName = childElement.getName(); if (!DAVElement.SVN_NAMESPACE.equals(childElementName.getNamespace())) { continue; } if (childElementName == DAVElement.PEG_REVISION) { try { myPegRevision = Long.parseLong(childElement.getFirstValue(true)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (childElementName == DAVElement.END_REVISION) { try { myEndRevision = Long.parseLong(childElement.getFirstValue(true)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (childElementName == DAVElement.PATH) { String path = childElement.getFirstValue(false); DAVPathUtil.testCanonical(path); myPath = path; } } } } } DAVGetHandler.java000066400000000000000000000205421177510526000356750ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; import org.tmatesoft.svn.util.Version; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVGetHandler extends ServletDAVHandler { public DAVGetHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); } public void execute() throws SVNException { DAVResource resource = getRequestedDAVResource(true, false); if (!resource.exists()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_PATH_NOT_FOUND, "Path ''{0}'' you requested not found", resource.getResourceURI().getPath()), SVNLogType.NETWORK); } if (resource.getResourceURI().getType() != DAVResourceType.REGULAR && resource.getResourceURI().getType() != DAVResourceType.VERSION && resource.getResourceURI().getType() != DAVResourceType.WORKING) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, "Cannot GET this type of resource."), SVNLogType.NETWORK); } setDefaultResponseHeaders(); setResponseHeaders(resource); try { checkPreconditions(resource.getETag(), resource.getLastModified()); } catch (SVNException e) { //Nothing to do, there are no enough conditions } if (resource.isCollection()) { StringBuffer body = new StringBuffer(); generateResponseBody(resource, body); String responseBody = body.toString(); try { setResponseContentLength(responseBody.getBytes(UTF8_ENCODING).length); } catch (UnsupportedEncodingException e) { setResponseContentLength(responseBody.getBytes().length); } try { getResponseWriter().write(responseBody); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } else if (resource.getDeltaBase() != null) { //Here we should send SVN delta (for old clients) } else { resource.writeTo(getResponseOutputStream()); } } protected DAVRequest getDAVRequest() { return null; } protected int checkPreconditions(String eTag, Date lastModified) { super.checkPreconditions(eTag, lastModified); lastModified = lastModified == null ? new Date() : lastModified; boolean isNotModified = false; Enumeration ifNoneMatch = getRequestHeaders(IF_NONE_MATCH_HEADER); if (ifNoneMatch != null && ifNoneMatch.hasMoreElements()) { if (eTag != null) { if (getRequestHeaders(RANGE_HEADER) != null && getRequestHeaders(RANGE_HEADER).hasMoreElements()) { isNotModified = !eTag.startsWith("W") && containsValue(ifNoneMatch, eTag, "*"); } else { isNotModified = containsValue(ifNoneMatch, eTag, "*"); } } } long ifModified = getRequestDateHeader(IF_MODIFIED_SINCE_HEADER); long date = getRequestDateHeader(DATE_HEADER); if ((isNotModified || ifNoneMatch == null || !ifNoneMatch.hasMoreElements()) && ifModified != -1 && date != -1) { isNotModified = ifModified >= lastModified.getTime() && ifModified <= date; } if (isNotModified) { // TODO status HTTP_NOT_MODIFIED } else { //TODO status OK } return 0;//TODO } private void setResponseHeaders(DAVResource resource) { try { setResponseContentType(resource.getContentType()); } catch (SVNException e) { //nothing to do we just skip this header } setResponseHeader(ACCEPT_RANGES_HEADER, ACCEPT_RANGES_DEFAULT_VALUE); try { Date lastModifiedTime = resource.getLastModified(); if (lastModifiedTime != null) { setResponseHeader(LAST_MODIFIED_HEADER, SVNDate.formatRFC1123Date(lastModifiedTime)); } } catch (SVNException e) { //nothing to do we just skip this header } String eTag = resource.getETag(); if (eTag != null) { setResponseHeader(ETAG_HEADER, eTag); } } private void generateResponseBody(DAVResource resource, StringBuffer buffer) throws SVNException { startBody(SVNPathUtil.tail(resource.getResourceURI().getContext()), resource.getResourceURI().getPath(), resource.getRevision(), buffer); addUpperDirectoryLink(resource.getResourceURI().getContext(), resource.getResourceURI().getPath(), buffer); addDirectoryEntries(resource, buffer); finishBody(buffer); } private void startBody(String contextComponent, String path, long revision, StringBuffer buffer) { buffer.append(""); buffer.append(contextComponent); buffer.append(" - Revision "); buffer.append(String.valueOf(revision)); buffer.append(": "); buffer.append(path); buffer.append("\n"); buffer.append("\n

"); buffer.append(contextComponent); buffer.append(" - Revision "); buffer.append(String.valueOf(revision)); buffer.append(": "); buffer.append(path); buffer.append("

\n
    \n"); } private void addUpperDirectoryLink(String context, String path, StringBuffer buffer) { if (!"/".equals(path)) { buffer.append("
  • ..
  • \n"); } } private void addDirectoryEntries(DAVResource resource, StringBuffer buffer) throws SVNException { for (Iterator iterator = resource.getEntries().iterator(); iterator.hasNext();) { SVNDirEntry entry = (SVNDirEntry) iterator.next(); boolean isDir = entry.getKind() == SVNNodeKind.DIR; buffer.append("
  • "); buffer.append(entry.getName()); buffer.append(isDir ? "/" : ""); buffer.append("
  • \n"); } } private void finishBody(StringBuffer buffer) { buffer.append("

"); buffer.append("Powered by "); buffer.append(Version.getVersionString()); buffer.append("\n"); } } DAVGetLocationSegmentsHandler.java000066400000000000000000000202001177510526000410630ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSLocationsFinder; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.ISVNLocationSegmentHandler; import org.tmatesoft.svn.core.io.SVNLocationSegment; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVGetLocationSegmentsHandler extends DAVReportHandler implements ISVNLocationSegmentHandler { private static final String GET_LOCATION_SEGMENTS_REPORT = "get-location-segments-report"; private static final String LOCATION_SEGMENT_TAG = "location-segment"; private static final String RANGE_START_ATTR = "range-start"; private static final String RANGE_END_ATTR = "range-end"; private DAVGetLocationSegmentsRequest myDAVRequest; private boolean myIsOpenerSent; private DAVReportHandler myCommonReportHandler; protected DAVGetLocationSegmentsHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(repositoryManager, request, response); myCommonReportHandler = commonReportHandler; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace(null); DAVResource resource = getRequestedDAVResource(false, false); setDAVResource(resource); DAVGetLocationSegmentsRequest request = getLocationSegmentsRequest(); String path = null; long startRev = -1; long endRev = -1; long pegRev = -1; DAVElementProperty rootElement = request.getRootElement(); List children = rootElement.getChildren(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { DAVElementProperty childElement = (DAVElementProperty) iterator.next(); DAVElement childElementName = childElement.getName(); if (!DAVElement.SVN_NAMESPACE.equals(childElementName.getNamespace())) { continue; } if (childElementName == DAVElement.PATH) { path = childElement.getFirstValue(false); DAVPathUtil.testCanonical(path); String resourcePath = resource.getResourceURI().getPath(); path = SVNPathUtil.append(resourcePath, path); } else if (childElementName == DAVElement.START_REVISION) { try { startRev = Long.parseLong(childElement.getFirstValue(true)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (childElementName == DAVElement.END_REVISION) { try { endRev = Long.parseLong(childElement.getFirstValue(true)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (childElementName == DAVElement.PEG_REVISION) { try { pegRev = Long.parseLong(childElement.getFirstValue(true)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } } if (path == null) { throw new DAVException("Not all parameters passed.", HttpServletResponse.SC_BAD_REQUEST, SVNLogType.NETWORK, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE); } if (SVNRevision.isValidRevisionNumber(startRev) && SVNRevision.isValidRevisionNumber(endRev) && endRev > startRev) { throw new DAVException("End revision must not be younger than start revision", HttpServletResponse.SC_BAD_REQUEST, SVNLogType.NETWORK, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE); } if (SVNRevision.isValidRevisionNumber(pegRev) && SVNRevision.isValidRevisionNumber(startRev) && startRev > pegRev) { throw new DAVException("Start revision must not be younger than peg revision", HttpServletResponse.SC_BAD_REQUEST, SVNLogType.NETWORK, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE); } FSLocationsFinder locationsFinder = new FSLocationsFinder(getDAVResource().getFSFS()); locationsFinder.getNodeLocationSegments(path, pegRev, startRev, endRev, this); try { maybeSendOpener(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error beginning REPORT reponse", null); } try { writeXMLFooter(GET_LOCATION_SEGMENTS_REPORT); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error ending REPORT reponse", null); } } public void handleLocationSegment(SVNLocationSegment locationSegment) throws SVNException { maybeSendOpener(); Map attrs = new HashMap(); String path = locationSegment.getPath(); if (path != null) { String quotedPath = SVNEncodingUtil.xmlEncodeCDATA(path, true); attrs.put(PATH_ATTR, quotedPath); attrs.put(RANGE_START_ATTR, String.valueOf(locationSegment.getStartRevision())); attrs.put(RANGE_END_ATTR, String.valueOf(locationSegment.getEndRevision())); } else { attrs.put(RANGE_START_ATTR, String.valueOf(locationSegment.getStartRevision())); attrs.put(RANGE_END_ATTR, String.valueOf(locationSegment.getEndRevision())); } StringBuffer buffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, LOCATION_SEGMENT_TAG, SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, null); write(buffer); } protected DAVRequest getDAVRequest() { return getLocationSegmentsRequest(); } private DAVGetLocationSegmentsRequest getLocationSegmentsRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVGetLocationSegmentsRequest(); } return myDAVRequest; } private void maybeSendOpener() throws SVNException { if (!myIsOpenerSent) { writeXMLHeader(GET_LOCATION_SEGMENTS_REPORT); myIsOpenerSent = true; } } } DAVGetLocationSegmentsRequest.java000066400000000000000000000016741177510526000411540ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import org.tmatesoft.svn.core.SVNException; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVGetLocationSegmentsRequest extends DAVRequest { public DAVGetLocationSegmentsRequest() { } protected void init() throws SVNException { } protected DAVElementProperty getRoot() { return getRootElement(); } } DAVGetLocationsHandler.java000066400000000000000000000100051177510526000375420ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.io.SVNLocationEntry; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVGetLocationsHandler extends DAVReportHandler { private static final String GET_LOCATIONS_REPORT = "get-locations-report"; private DAVGetLocationsRequest myDAVRequest; private DAVReportHandler myCommonReportHandler; public DAVGetLocationsHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(repositoryManager, request, response); myCommonReportHandler = commonReportHandler; } protected DAVRequest getDAVRequest() { return getGetLocationsRequest(); } private DAVGetLocationsRequest getGetLocationsRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVGetLocationsRequest(); } return myDAVRequest; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace(null); setDAVResource(getRequestedDAVResource(false, false)); DAVResource resource = getDAVResource(); DAVGetLocationsRequest request = getGetLocationsRequest(); String path = request.getPath(); long pegRevision = request.getPegRevision(); if (path == null || !SVNRevision.isValidRevisionNumber(pegRevision)) { throw new DAVException("Not all parameters passed.", HttpServletResponse.SC_BAD_REQUEST, SVNLogType.NETWORK, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE); } if (!path.startsWith("/")) { path = SVNPathUtil.append(resource.getResourceURI().getPath(), path); } SVNRepository repository = resource.getRepository(); Collection locations = repository.getLocations(path, (Collection)null, pegRevision, request.getRevisions()); Map attrs = new SVNHashMap(); writeXMLHeader(GET_LOCATIONS_REPORT); for (Iterator locationsIter = locations.iterator(); locationsIter.hasNext();) { SVNLocationEntry locationEntry = (SVNLocationEntry) locationsIter.next(); attrs.clear(); attrs.put(PATH_ATTR, locationEntry.getPath()); attrs.put(REVISION_ATTR, String.valueOf(locationEntry.getRevision())); StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "location", SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, null); write(xmlBuffer); } writeXMLFooter(GET_LOCATIONS_REPORT); } } DAVGetLocationsRequest.java000066400000000000000000000111221177510526000376160ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVGetLocationsRequest extends DAVRequest { private static final DAVElement GET_LOCATIONS_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "get-locations-report"); private static final DAVElement PEG_REVISION = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "peg-revision"); private static final DAVElement LOCATION_REVISION = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "location-revision"); private String myPath = null; private long myPegRevision = DAVResource.INVALID_REVISION; private Collection myRevisions; private long[] myRevisionsArray; public String getPath() { return myPath; } private void setPath(String path) { myPath = path; } public long getPegRevision() { return myPegRevision; } private void setPegRevision(long pegRevision) { myPegRevision = pegRevision; } public long[] getRevisions() { if (myRevisionsArray != null) { return myRevisionsArray; } if (myRevisions != null) { myRevisionsArray = new long[myRevisions.size()]; int i = 0; for (Iterator revObjectsIter = myRevisions.iterator(); revObjectsIter.hasNext(); i++) { Long revisionObject = (Long) revObjectsIter.next(); myRevisionsArray[i] = revisionObject.longValue(); } myRevisions = null; return myRevisionsArray; } return null; } private void addRevision(long revision) { if (myRevisions == null) { myRevisions = new LinkedList(); } myRevisions.add(new Long(revision)); } protected void init() throws SVNException { getRootElement().setElementName(GET_LOCATIONS_REPORT); List children = getRootElement().getChildren(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { DAVElementProperty property = (DAVElementProperty) iterator.next(); DAVElement element = property.getName(); if (element == DAVElement.PATH) { String path = property.getFirstValue(false); DAVPathUtil.testCanonical(path); setPath(path); } else if (element == PEG_REVISION) { String pegRevisionString = property.getFirstValue(true); try { setPegRevision(Long.parseLong(pegRevisionString)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (element == LOCATION_REVISION) { for (Iterator revisionsIterator = property.getValues().iterator(); revisionsIterator.hasNext(); ) { try { addRevision(Long.parseLong((String) revisionsIterator.next())); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } } } if (getPath() == null && !SVNRevision.isValidRevisionNumber(getPegRevision())) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Not all parameters passed."), SVNLogType.NETWORK); } } } DAVGetLocksHandler.java000066400000000000000000000122671177510526000366760ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.util.SVNBase64; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVGetLocksHandler extends DAVReportHandler { private DAVGetLocksRequest myDAVRequest; protected DAVGetLocksHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } protected DAVRequest getDAVRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVGetLocksRequest(); } return myDAVRequest; } public void execute() throws SVNException { setDAVResource(getRequestedDAVResource(false, false)); String responseBody = generateResponseBody(); try { setResponseContentLength(responseBody.getBytes(UTF8_ENCODING).length); } catch (UnsupportedEncodingException e) { } write(responseBody); } private String generateResponseBody() throws SVNException { if (getDAVResource().getResourceURI().getPath() == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "get-locks-report run on resource which doesn't represent a path within a repository."), SVNLogType.NETWORK); } SVNLock[] locks = getDAVResource().getLocks(); StringBuffer xmlBuffer = new StringBuffer(); addXMLHeader(xmlBuffer, null); for (int i = 0; i < locks.length; i++) { addLock(locks[i], xmlBuffer); } addXMLFooter(xmlBuffer, null); return xmlBuffer.toString(); } private void addLock(SVNLock lock, StringBuffer xmlBuffer) { SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "lock", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "path", lock.getPath(), xmlBuffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "token", lock.getID(), xmlBuffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "creationdate", SVNDate.formatDate(lock.getCreationDate()), xmlBuffer); if (lock.getExpirationDate() != null) { SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "expirationdate", SVNDate.formatDate(lock.getExpirationDate()), xmlBuffer); } if (lock.getOwner() != null) { if (SVNEncodingUtil.isXMLSafe(lock.getOwner())) { SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "owner", lock.getOwner(), xmlBuffer); } else { String ownerEncoded = null; try { ownerEncoded = SVNBase64.byteArrayToBase64(lock.getOwner().getBytes(UTF8_ENCODING)); } catch (UnsupportedEncodingException e) { ownerEncoded = SVNBase64.byteArrayToBase64(lock.getOwner().getBytes()); } SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "owner", ownerEncoded, ENCODING_ATTR, BASE64_ENCODING, false, false, xmlBuffer); } } if (lock.getComment() != null) { if (SVNEncodingUtil.isXMLSafe(lock.getComment())) { SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "comment", lock.getComment(), xmlBuffer); } else { String commentEncoded = null; try { commentEncoded = SVNBase64.byteArrayToBase64(lock.getComment().getBytes(UTF8_ENCODING)); } catch (UnsupportedEncodingException e) { commentEncoded = SVNBase64.byteArrayToBase64(lock.getComment().getBytes()); } SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "comment", commentEncoded, ENCODING_ATTR, BASE64_ENCODING, false, false, xmlBuffer); } } SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "lock", xmlBuffer); } } DAVGetLocksRequest.java000066400000000000000000000014421177510526000367420ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import org.tmatesoft.svn.core.SVNException; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVGetLocksRequest extends DAVRequest { protected void init() throws SVNException { } } DAVHandlerFactory.java000066400000000000000000000110701177510526000365610ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVHandlerFactory { public static final String METHOD_PROPFIND = "PROPFIND"; public static final String METHOD_OPTIONS = "OPTIONS"; public static final String METHOD_REPORT = "REPORT"; public static final String METHOD_GET = "GET"; public static final String METHOD_HEAD = "HEAD"; public static final String METHOD_POST = "POST"; public static final String METHOD_DELETE = "DELETE"; public static final String METHOD_TRACE = "TRACE"; public static final String METHOD_PROPPATCH = "PROPPATCH"; public static final String METHOD_COPY = "COPY"; public static final String METHOD_MOVE = "MOVE"; public static final String METHOD_PUT = "PUT"; public static final String METHOD_LOCK = "LOCK"; public static final String METHOD_UNLOCK = "UNLOCK"; public static final String METHOD_MKCOL = "MKCOL"; public static final String METHOD_VERSION_CONTROL = "VERSION-CONTROL"; public static final String METHOD_MKWORKSPACE = "MKWORKSPACE"; public static final String METHOD_MKACTIVITY = "MKACTIVITY"; public static final String METHOD_CHECKIN = "CHECKIN"; public static final String METHOD_CHECKOUT = "CHECKOUT"; public static final String METHOD_MERGE = "MERGE"; public static ServletDAVHandler createHandler(DAVRepositoryManager manager, HttpServletRequest request, HttpServletResponse response) throws SVNException { String methodName = request.getMethod(); if (METHOD_PROPFIND.equals(methodName)) { return new DAVPropfindHandler(manager, request, response); } else if (METHOD_OPTIONS.equals(methodName)) { return new DAVOptionsHandler(manager, request, response); } else if (METHOD_GET.equals(methodName)) { return new DAVGetHandler(manager, request, response); } else if (METHOD_REPORT.equals(methodName)) { return new DAVReportHandler(manager, request, response); } else if (METHOD_MKACTIVITY.equals(methodName)) { return new DAVMakeActivityHandler(manager, request, response); } else if (METHOD_CHECKOUT.equals(methodName)) { return new DAVCheckOutHandler(manager, request, response); } else if (METHOD_PUT.equals(methodName)) { return new DAVPutHandler(manager, request, response); } else if (METHOD_DELETE.equals(methodName)) { return new DAVDeleteHandler(manager, request, response); } else if (METHOD_COPY.equals(methodName)) { return new DAVCopyMoveHandler(manager, request, response, false); } else if (METHOD_MOVE.equals(methodName)) { return new DAVCopyMoveHandler(manager, request, response, true); } else if (METHOD_MKCOL.equals(methodName)) { return new DAVMakeCollectionHandler(manager, request, response); } else if (METHOD_PROPPATCH.equals(methodName)) { return new DAVPropPatchHandler(manager, request, response); } else if (METHOD_MERGE.equals(methodName)) { return new DAVMergeHandler(manager, request, response); } else if (METHOD_LOCK.equals(methodName)) { return new DAVLockHandler(manager, request, response); } else if (METHOD_UNLOCK.equals(methodName)) { return new DAVUnlockHandler(manager, request, response); } SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Unknown request method ''{0}''", request.getMethod()), SVNLogType.NETWORK); return null; } }DAVInheritWalker.java000066400000000000000000000032631177510526000364310ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.LinkedList; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVInheritWalker implements IDAVResourceWalkHandler { private boolean myIsSkipRoot; private DAVResource myResource; private DAVLock myLock; public DAVInheritWalker(DAVResource resource, DAVLock lock, boolean skipRoot) { myResource = resource; myIsSkipRoot = skipRoot; myLock = lock; } public DAVResponse handleResource(DAVResponse response, DAVResource resource, DAVLockInfoProvider lockInfoProvider, LinkedList ifHeaders, int flags, DAVLockScope lockScope, CallType callType) throws DAVException { if (myIsSkipRoot && myResource.equals(resource)) { return null; } lockInfoProvider.appendLock(resource, myLock); return null; } } DAVLockHandler.java000066400000000000000000000145641177510526000360550ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPHeader; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceState; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVLockHandler extends ServletDAVHandler { private DAVLockRequest myLockRequest; protected DAVLockHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } public void execute() throws SVNException { long readLength = readInput(false); DAVDepth depth = null; try { depth = getRequestDepth(DAVDepth.DEPTH_INFINITY); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_BAD_REQUEST, null, null); } if (depth != DAVDepth.DEPTH_ZERO && depth != DAVDepth.DEPTH_INFINITY) { sendError(HttpServletResponse.SC_BAD_REQUEST, "Depth must be 0 or \"infinity\" for LOCK."); return; } DAVLockInfoProvider lockProvider = null; DAVResource resource = getRequestedDAVResource(false, false); try { lockProvider = DAVLockInfoProvider.createLockInfoProvider(this, false); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, null); } boolean isNewLockRequest = false; DAVLock lock = null; if (readLength > 0) { lock = getLockRequest().parseLockInfo(this, resource, getNamespaces()); isNewLockRequest = true; } DAVResourceState resourceState = getResourceState(resource); try { int flags = resourceState == DAVResourceState.NULL ? DAV_VALIDATE_PARENT : DAV_VALIDATE_RESOURCE; flags |= DAV_VALIDATE_ADD_LD; validateRequest(resource, depth, flags, isNewLockRequest ? lock.getScope() : null, null, lockProvider); } catch (DAVException dave) { DAVException next = new DAVException("Could not LOCK {0} due to a failed precondition (e.g. other locks).", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI(), true) }, dave.getResponseCode(), dave, 0); throw next; } if (!isNewLockRequest) { List lockTokens = null; try { lockTokens = getLockTokensList(); } catch (DAVException dave) { DAVException next = new DAVException("The lock refresh for {0} failed because no lock tokens were specified in an \"If:\" header.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI(), true) }, dave.getResponseCode(), dave, 0); throw next; } String lockToken = (String) lockTokens.get(0); lock = lockProvider.refreshLock(resource, lockToken, getTimeout()); } else { if (lock.getTimeOutDate() != null) { //TODO: add expiration date renewal //Date timeoutDate = lock.getTimeOutDate(); } lockProvider.addLock(lock, resource); setResponseHeader(HTTPHeader.LOCK_TOKEN_HEADER, "<" + lock.getLockToken() + ">"); } HttpServletResponse servletResponse = getHttpServletResponse(); servletResponse.setContentType(DEFAULT_XML_CONTENT_TYPE); servletResponse.setStatus(HttpServletResponse.SC_OK); try { StringBuffer xmlBuffer = SVNXMLUtil.addXMLHeader(null); DAVXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), null, null, xmlBuffer, true, false); if (lock == null) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_DISCOVERY.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, xmlBuffer); } else { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_DISCOVERY.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, xmlBuffer); xmlBuffer.append(DAVLockInfoProvider.getActiveLockXML(lock)); xmlBuffer.append('\n'); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_DISCOVERY.getName(), xmlBuffer); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), xmlBuffer); getResponseWriter().write(xmlBuffer.toString()); } catch (IOException e) { throw new DAVException(e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } } protected DAVRequest getDAVRequest() { return getLockRequest(); } private DAVLockRequest getLockRequest() { if (myLockRequest == null) { myLockRequest = new DAVLockRequest(); } return myLockRequest; } } DAVLockInfoProvider.java000066400000000000000000000661421177510526000371050ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.dav.handlers.BasicDAVHandler; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPHeader; import org.tmatesoft.svn.core.internal.io.fs.FSCommitter; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSLock; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionRoot; import org.tmatesoft.svn.core.internal.server.dav.DAVConfig; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVErrorCode; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVLockRecType; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVLockType; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceHelper; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceURI; import org.tmatesoft.svn.core.internal.server.dav.DAVServletUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVLockInfoProvider { public static final String LOCK_BREAK_OPTION = "lock-break"; public static final String LOCK_STEAL_OPTION = "lock-steal"; public static final String RELEASE_LOCKS_OPTION = "release-locks"; public static final String KEEP_LOCKS_OPTION = "keep-locks"; public static final String NO_MERGE_RESPONSE = "no-merge-response"; private boolean myIsReadOnly; private boolean myIsStealLock; private boolean myIsBreakLock; private boolean myIsKeepLocks; private long myWorkingRevision; private ServletDAVHandler myOwner; public static DAVLockInfoProvider createLockInfoProvider(ServletDAVHandler owner, boolean readOnly) throws SVNException { String clientOptions = owner.getRequestHeader(ServletDAVHandler.SVN_OPTIONS_HEADER); DAVLockInfoProvider provider = new DAVLockInfoProvider(); provider.myOwner = owner; provider.myIsReadOnly = readOnly; if (clientOptions != null) { if (clientOptions.indexOf(LOCK_BREAK_OPTION) != -1) { provider.myIsBreakLock = true; } if (clientOptions.indexOf(LOCK_STEAL_OPTION) != -1) { provider.myIsStealLock = true; } if (clientOptions.indexOf(KEEP_LOCKS_OPTION) != -1) { provider.myIsKeepLocks = true; } } String versionName = owner.getRequestHeader(ServletDAVHandler.SVN_VERSION_NAME_HEADER); provider.myWorkingRevision = SVNRepository.INVALID_REVISION; if (versionName != null) { try { provider.myWorkingRevision = Long.parseLong(versionName); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } return provider; } public void addLock(DAVLock lock, DAVResource resource) throws DAVException { DAVDepth depth = lock.getDepth(); if (!resource.isCollection()) { depth = DAVDepth.DEPTH_ZERO; } appendLock(resource, lock); if (depth != DAVDepth.DEPTH_ZERO) { DAVResourceWalker walker = new DAVResourceWalker(); DAVLockWalker lockHandler = new DAVLockWalker(resource, lock); DAVResponse response = walker.walk(this, resource, null, 0, null, DAVResourceWalker.DAV_WALKTYPE_NORMAL | DAVResourceWalker.DAV_WALKTYPE_AUTH, lockHandler, DAVDepth.DEPTH_INFINITY); if (response != null) { throw new DAVException("Error(s) occurred on resources during the addition of a depth lock.", ServletDAVHandler.SC_MULTISTATUS, 0, response); } } } public DAVLock refreshLock(DAVResource resource, String lockToken, Date newTime) throws DAVException { //TODO: add here authz check FSFS fsfs = resource.getFSFS(); String path = resource.getResourceURI().getPath(); FSLock svnLock = null; try { svnLock = (FSLock) fsfs.getLockHelper(path, false); } catch (SVNException e) { throw DAVException.convertError(e.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Token doesn't point to a lock.", null); } if (svnLock == null || !svnLock.getID().equals(lockToken)) { throw new DAVException("Lock refresh request doesn't match existing lock.", HttpServletResponse.SC_UNAUTHORIZED, DAVErrorCode.LOCK_SAVE_LOCK); } try { svnLock = (FSLock) fsfs.lockPath(svnLock.getPath(), svnLock.getID(), resource.getUserName(), svnLock.getComment(), newTime, SVNRepository.INVALID_REVISION, true, svnLock.isDAVComment()); } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.FS_NO_USER) { throw new DAVException("Anonymous lock refreshing is not allowed.", HttpServletResponse.SC_UNAUTHORIZED, DAVErrorCode.LOCK_SAVE_LOCK); } throw DAVException.convertError(err, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to refresh existing lock.", null); } return convertSVNLockToDAVLock(svnLock, false, resource.exists()); } public void inheritLocks(DAVResource resource, boolean useParent) throws DAVException { DAVResource whichResource = resource; if (useParent) { DAVResource parentResource = DAVResourceHelper.createParentResource(resource); if (parentResource == null) { throw new DAVException("Could not fetch parent resource. Unable to inherit locks from the parent and apply them to this resource.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } whichResource = parentResource; } DAVLock lock = getLock(whichResource); if (lock == null) { return; } DAVInheritWalker inheritHandler = new DAVInheritWalker(resource, lock, !useParent); DAVResourceWalker walker = new DAVResourceWalker(); walker.walk(this, whichResource, null, 0, null, DAVResourceWalker.DAV_WALKTYPE_NORMAL | DAVResourceWalker.DAV_WALKTYPE_LOCKNULL, inheritHandler, DAVDepth.DEPTH_INFINITY); } public void appendLock(DAVResource resource, DAVLock lock) throws DAVException { //TODO: add here authz check later FSFS fsfs = resource.getFSFS(); String path = resource.getResourceURI().getPath(); if (!resource.exists()) { SVNProperties revisionProps = new SVNProperties(); revisionProps.put(SVNRevisionProperty.AUTHOR, resource.getUserName()); DAVConfig config = resource.getRepositoryManager().getDAVConfig(); if (resource.isSVNClient()) { throw new DAVException("Subversion clients may not lock nonexistent paths.", HttpServletResponse.SC_METHOD_NOT_ALLOWED, DAVErrorCode.LOCK_SAVE_LOCK); } else if (!config.isAutoVersioning()) { throw new DAVException("Attempted to lock non-existent path; turn on autoversioning first.", HttpServletResponse.SC_METHOD_NOT_ALLOWED, DAVErrorCode.LOCK_SAVE_LOCK); } long youngestRev = SVNRepository.INVALID_REVISION; try { youngestRev = resource.getLatestRevision(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not determine youngest revision", null); } FSTransactionInfo txnInfo = null; try { txnInfo = FSTransactionRoot.beginTransactionForCommit(youngestRev, revisionProps, fsfs); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not begin a transaction", null); } FSTransactionRoot root = null; try { root = fsfs.createTransactionRoot(txnInfo); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not begin a transaction", null); } FSCommitter committer = new FSCommitter(fsfs, root, txnInfo, resource.getLockTokens(), resource.getUserName()); try { committer.makeFile(path); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create empty file.", null); } try { DAVServletUtil.attachAutoRevisionProperties(txnInfo, path, fsfs); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create empty file.", null); } StringBuffer conflictPath = new StringBuffer(); try { committer.commitTxn(true, true, null, conflictPath); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_CONFLICT, "Conflict when committing ''{0}''.", new Object[] { conflictPath.toString() }); } } FSLock svnLock = convertDAVLockToSVNLock(lock, path, resource.isSVNClient(), ServletDAVHandler.getSAXParserFactory()); try { fsfs.lockPath(path, svnLock.getID(), svnLock.getOwner(), svnLock.getComment(), svnLock.getExpirationDate(), myWorkingRevision, myIsStealLock, svnLock.isDAVComment()); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NO_USER) { throw new DAVException("Anonymous lock creation is not allowed.", HttpServletResponse.SC_UNAUTHORIZED, DAVErrorCode.LOCK_SAVE_LOCK); } throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create new lock.", null); } myOwner.setResponseHeader(HTTPHeader.CREATION_DATE_HEADER, SVNDate.formatDate(svnLock.getCreationDate())); myOwner.setResponseHeader(HTTPHeader.LOCK_OWNER_HEADER, svnLock.getOwner()); //TODO: add logging here later } public boolean hasLocks(DAVResource resource) throws DAVException { if (resource.getResourceURI().getPath() == null) { return false; } if (DAVHandlerFactory.METHOD_LOCK.equals(myOwner.getRequestMethod())) { return false; } //TODO: add authz check here later SVNLock lock = null; try { lock = resource.getLock(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to check path for a lock.", null); } return lock != null; } public DAVLock getLock(DAVResource resource) throws DAVException { if (resource.getResourceURI().getPath() == null) { return null; } if (DAVHandlerFactory.METHOD_LOCK.equals(myOwner.getRequestMethod())) { return null; } //TODO: add authz check here later DAVLock davLock = null; FSLock lock = null; try { lock = (FSLock) resource.getLock(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to check path for a lock.", null); } if (lock != null) { davLock = convertSVNLockToDAVLock(lock, myIsBreakLock, resource.exists()); myOwner.setResponseHeader(HTTPHeader.CREATION_DATE_HEADER, SVNDate.formatDate(lock.getCreationDate())); myOwner.setResponseHeader(HTTPHeader.LOCK_OWNER_HEADER, lock.getOwner()); } return davLock; } public DAVLock findLock(DAVResource resource, String lockToken) throws DAVException { //TODO: add here authz check later DAVLock davLock = null; FSLock lock = null; try { lock = (FSLock) resource.getLock(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to look up lock by path.", null); } if (lock != null) { if (!lockToken.equals(lock.getID())) { throw new DAVException("Incoming token doesn't match existing lock.", HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.LOCK_SAVE_LOCK); } davLock = convertSVNLockToDAVLock(lock, false, resource.exists()); myOwner.setResponseHeader(HTTPHeader.CREATION_DATE_HEADER, SVNDate.formatDate(lock.getCreationDate())); myOwner.setResponseHeader(HTTPHeader.LOCK_OWNER_HEADER, lock.getOwner()); } return davLock; } public void removeLock(DAVResource resource, String lockToken) throws DAVException { DAVResourceURI resourceURI = resource.getResourceURI(); if (resourceURI.getPath() == null) { return; } if (isKeepLocks()) { return; } //TODO: add here authz check later String token = null; SVNLock lock = null; if (lockToken == null) { try { lock = resource.getLock(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to check path for a lock.", null); } if (lock != null) { token = lock.getID(); } } else { token = lockToken; } if (token != null) { try { resource.unlock(token, isBreakLock()); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NO_USER) { throw new DAVException("Anonymous lock removal is not allowed.", HttpServletResponse.SC_UNAUTHORIZED, DAVErrorCode.LOCK_SAVE_LOCK); } throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to remove a lock.", null); } //TODO: add logging here } } public String getSupportedLock(DAVResource resource) { if (resource.isCollection()) { return null; } StringBuffer buffer = new StringBuffer(); buffer.append('\n'); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_ENTRY.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_SCOPE.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.EXCLUSIVE.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_SCOPE.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TYPE.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.WRITE.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TYPE.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_ENTRY.getName(), buffer); return buffer.toString(); } public boolean isReadOnly() { return myIsReadOnly; } public boolean isStealLock() { return myIsStealLock; } public boolean isBreakLock() { return myIsBreakLock; } public boolean isKeepLocks() { return myIsKeepLocks; } public long getWorkingRevision() { return myWorkingRevision; } public static String getActiveLockXML(DAVLock lock) { StringBuffer buffer = new StringBuffer(); if (lock == null) { return ""; } if (lock.getRecType() == DAVLockRecType.INDIRECT_PARTIAL) { //TODO: add debugging message here? } SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.ACTIVE_LOCK.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TYPE.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); if (lock.getType() == DAVLockType.WRITE) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.WRITE.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); } else { //TODO: internal error. log something? } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TYPE.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_SCOPE.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); if (lock.getScope() == DAVLockScope.EXCLUSIVE) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.EXCLUSIVE.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); } else if (lock.getScope() == DAVLockScope.SHARED) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.SHARED.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); } else { //TODO: internal error. log something? } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_SCOPE.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.DEPTH.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append(lock.getDepth() == DAVDepth.DEPTH_INFINITY ? DAVDepth.DEPTH_INFINITY.toString() : DAVDepth.DEPTH_ZERO.toString()); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.DEPTH.getName(), buffer); if (lock.getOwner() != null) { buffer.append(lock.getOwner()); } SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TIMEOUT.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); if (lock.getTimeOutDate() == null) { buffer.append("Infinite"); } else { Date timeOutDate = lock.getTimeOutDate(); long now = System.currentTimeMillis(); long diff = timeOutDate.getTime() - now; buffer.append("Second-"); //TODO: I'm not sure if I clearly understand what we must send here, //have to test and review this later buffer.append(diff); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TIMEOUT.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TOKEN.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append(lock.getLockToken()); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_TOKEN.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.ACTIVE_LOCK.getName(), buffer); return buffer.toString(); } public static FSLock convertDAVLockToSVNLock(DAVLock davLock, String path, boolean isSVNClient, SAXParserFactory saxParserFactory) throws DAVException { if (davLock.getType() != DAVLockType.WRITE) { throw new DAVException("Only 'write' locks are supported.", HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.LOCK_SAVE_LOCK); } if (davLock.getScope() != DAVLockScope.EXCLUSIVE) { throw new DAVException("Only exclusive locks are supported.", HttpServletResponse.SC_BAD_REQUEST, DAVErrorCode.LOCK_SAVE_LOCK); } boolean isDAVComment = false; String comment = null; if (davLock.getOwner() != null) { if (isSVNClient) { try { SAXParser xmlParser = saxParserFactory.newSAXParser(); XMLReader reader = xmlParser.getXMLReader(); FetchXMLHandler handler = new FetchXMLHandler(DAVElement.LOCK_OWNER); reader.setContentHandler(handler); reader.setDTDHandler(handler); reader.setErrorHandler(handler); reader.setEntityResolver(handler); String owner = "" + davLock.getOwner(); reader.parse(new InputSource(new ByteArrayInputStream(owner.getBytes()))); comment = handler.getData(); } catch (ParserConfigurationException e) { throw new DAVException(e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DAVErrorCode.LOCK_SAVE_LOCK); } catch (SAXException e) { throw new DAVException(e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DAVErrorCode.LOCK_SAVE_LOCK); } catch (IOException e) { throw new DAVException(e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DAVErrorCode.LOCK_SAVE_LOCK); } } else { isDAVComment = true; comment = davLock.getOwner(); } } return new FSLock(path, davLock.getLockToken(), davLock.getAuthUser(), comment, new Date(System.currentTimeMillis()), davLock.getTimeOutDate(), isDAVComment); } public static DAVLock convertSVNLockToDAVLock(FSLock lock, boolean hideAuthUser, boolean exists) { String authUser = null; StringBuffer owner = null; if (lock.getComment() != null) { owner = new StringBuffer(); if (!lock.isDAVComment()) { List namespaces = new ArrayList(1); namespaces.add(DAVElement.DAV_NAMESPACE); owner = DAVXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_OWNER.getName(), namespaces, null, owner, false, false); owner.append(SVNEncodingUtil.xmlEncodeCDATA(lock.getComment(), true)); owner = SVNXMLUtil.addXMLFooter(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.LOCK_OWNER.getName(), owner); } else { owner.append(lock.getComment()); } } if (!hideAuthUser) { authUser = lock.getOwner(); } return new DAVLock(authUser, DAVDepth.DEPTH_ZERO, exists, lock.getID(), owner != null ? owner.toString() : null, DAVLockRecType.DIRECT, DAVLockScope.EXCLUSIVE, DAVLockType.WRITE, lock.getExpirationDate()); } public static class GetLocksCallType { public static final GetLocksCallType RESOLVED = new GetLocksCallType(); public static final GetLocksCallType PARTIAL = new GetLocksCallType(); public static final GetLocksCallType COMPLETE = new GetLocksCallType(); private GetLocksCallType() { } } private static class FetchXMLHandler extends BasicDAVHandler { private String myData; private DAVElement myElement; public FetchXMLHandler(DAVElement element) { myElement = element; init(); } public String getData() { return myData; } protected void endElement(DAVElement parent, DAVElement element, StringBuffer cdata) throws SVNException { if (element == myElement) { myData = cdata.toString(); } } protected void startElement(DAVElement parent, DAVElement element, Attributes attrs) throws SVNException { } } } DAVLockRequest.java000066400000000000000000000201311177510526000361130ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVLockRecType; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVLockType; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVLockRequest extends DAVRequest { private static final DAVElement LOCK_INFO = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "lockinfo"); public DAVLock parseLockInfo(DAVLockHandler handler, DAVResource resource, List namespaces) throws DAVException { DAVDepth depth = null; try { depth = handler.getRequestDepth(DAVDepth.DEPTH_INFINITY); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_BAD_REQUEST, null, null); } if (depth != DAVDepth.DEPTH_ONE && depth != DAVDepth.DEPTH_ZERO) { throw new DAVException("An invalid Depth header was specified.", HttpServletResponse.SC_BAD_REQUEST, 0); } Date timeout = handler.getTimeout(); String lockToken = null; try { lockToken = FSRepositoryUtil.generateLockToken(); } catch (SVNException e) { DAVException first = DAVException.convertError(e.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to generate a lock token.", null); DAVException next = new DAVException("Could not parse the lockinfo due to an internal problem creating a lock structure.", first.getResponseCode(), first, 0); throw next; } DAVElementProperty rootElement = null; try { rootElement = getRoot(); } catch (SVNException e) { throw DAVException.convertError(e.getErrorMessage(), HttpServletResponse.SC_BAD_REQUEST, "Could not parse the lockinfo, malformed xml request", null); } String owner = null; DAVLockScope lockScope = DAVLockScope.UNKNOWN; DAVLockType lockType = DAVLockType.UNKNOWN; for (Iterator childrenIter = rootElement.getChildren().iterator(); childrenIter.hasNext();) { DAVElementProperty childElement = (DAVElementProperty) childrenIter.next(); DAVElement childElementName = childElement.getName(); if (childElementName == DAVElement.LOCK_TYPE && childElement.getChildren() != null && lockType == DAVLockType.UNKNOWN) { DAVElementProperty writeChild = childElement.getChild(DAVElement.WRITE); if (writeChild != null) { lockType = DAVLockType.WRITE; continue; } } if (childElementName == DAVElement.LOCK_SCOPE && childElement.getChildren() != null && lockScope == DAVLockScope.UNKNOWN) { if (childElement.getChild(DAVElement.EXCLUSIVE) != null) { lockScope = DAVLockScope.EXCLUSIVE; } else if (childElement.getChild(DAVElement.SHARED) != null) { lockScope = DAVLockScope.SHARED; } if (lockScope != DAVLockScope.UNKNOWN) { continue; } } if (childElementName == DAVElement.LOCK_OWNER) { //TODO: maybe make this recursive for all possible subelements StringBuffer buffer = new StringBuffer(); String namespace = childElementName.getNamespace(); buffer.append("<"); if (namespace == null || "".equals(namespace)) { buffer.append(childElementName.getName()); } else { buffer.append(SVNXMLUtil.PREFIX_MAP.get(namespace)); buffer.append(":"); buffer.append(childElementName.getName()); } Map attributes = childElement.getAttributes(); if (attributes != null) { for (Iterator attrsIter = attributes.keySet().iterator(); attrsIter.hasNext();) { String attrName = (String) attrsIter.next(); String attrValue = (String) attributes.get(attrName); buffer.append(" "); buffer.append(attrName); buffer.append("=\""); buffer.append(attrValue); buffer.append("\""); } } for (Iterator namespacesIter = namespaces.iterator(); namespacesIter.hasNext();) { String nextNamespace = (String) namespacesIter.next(); buffer.append(" xmlns:"); buffer.append(SVNXMLUtil.PREFIX_MAP.get(nextNamespace)); buffer.append("=\""); buffer.append(nextNamespace); buffer.append("\""); } if (childElement.isEmpty()) { buffer.append(" />"); } else { buffer.append(">"); buffer.append(SVNEncodingUtil.xmlEncodeCDATA(childElement.getFirstValue(false), false)); buffer.append(""); } owner = buffer.toString(); continue; } throw new DAVException("The server cannot satisfy the LOCK request due to an unknown XML element (\"{0}\") within the DAV:lockinfo element.", new Object[] { childElementName.getName() }, HttpServletResponse.SC_PRECONDITION_FAILED, 0); } return new DAVLock(resource.getUserName(), depth, resource.exists(), lockToken, owner, DAVLockRecType.DIRECT, lockScope, lockType, timeout); } protected void init() throws SVNException { if (getRoot().getName() != LOCK_INFO) { invalidXMLRoot(); } } protected DAVElementProperty getRoot() throws SVNException { if (getRootElement() == null) { invalidXMLRoot(); } return getRootElement(); } protected void invalidXMLRoot() throws SVNException { throw new DAVException("The request body contains an unexpected XML root element.", null, HttpServletResponse.SC_BAD_REQUEST, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } } DAVLockWalker.java000066400000000000000000000037531177510526000357230ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.LinkedList; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVLockWalker implements IDAVResourceWalkHandler { private DAVResource myResource; private DAVLock myLock; public DAVLockWalker(DAVResource resource, DAVLock lock) { myResource = resource; myLock = lock; } public DAVResponse handleResource(DAVResponse response, DAVResource resource, DAVLockInfoProvider lockInfoProvider, LinkedList ifHeaders, int flags, DAVLockScope lockScope, CallType callType) throws DAVException { if (myResource.equals(resource)) { return null; } try { lockInfoProvider.appendLock(resource, myLock); } catch (DAVException dave) { if (DAVServlet.isHTTPServerError(dave.getResponseCode())) { throw dave; } DAVResponse resp = new DAVResponse(null, resource.getResourceURI().getRequestURI(), response, null, dave.getResponseCode()); return resp; } return null; } } DAVLogHandler.java000066400000000000000000000204551177510526000357020ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.SVNLogEntryPath; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.wc.SVNRevision; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVLogHandler extends DAVReportHandler implements ISVNLogEntryHandler { private DAVLogRequest myDAVRequest; private int myDepth = 0; private DAVReportHandler myCommonReportHandler; public DAVLogHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(repositoryManager, request, response); myCommonReportHandler = commonReportHandler; } protected DAVRequest getDAVRequest() { return getLogRequest(); } private DAVLogRequest getLogRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVLogRequest(); } return myDAVRequest; } private int getDepth() { return myDepth; } private void increaseDepth() { myDepth++; } private void decreaseDepth() { myDepth--; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace(null); setDAVResource(getRequestedDAVResource(false, false)); writeXMLHeader(null); for (int i = 0; i < getLogRequest().getTargetPaths().length; i++) { String currentPath = getLogRequest().getTargetPaths()[i]; DAVPathUtil.testCanonical(currentPath); getLogRequest().getTargetPaths()[i] = SVNPathUtil.append(getDAVResource().getResourceURI().getPath(), currentPath); } DAVLogRequest logRequest = getLogRequest(); getDAVResource().getRepository().log(logRequest.getTargetPaths(), logRequest.getStartRevision(), logRequest.getEndRevision(), logRequest.isDiscoverChangedPaths(), logRequest.isStrictNodeHistory(), logRequest.getLimit(), logRequest.isIncludeMergedRevisions(), logRequest.getRevisionProperties(), this); writeXMLFooter(null); } public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { if (logEntry.getRevision() == DAVResource.INVALID_REVISION) { if (getDepth() == 0) { return; } decreaseDepth(); } StringBuffer xmlBuffer = new StringBuffer(); SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "log-item", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.VERSION_NAME.getName(), String.valueOf(logEntry.getRevision()), xmlBuffer); boolean noCustomProperties = getLogRequest().isCustomPropertyRequested(); SVNProperties revProps = logEntry.getRevisionProperties(); for (Iterator iterator = revProps.nameSet().iterator(); iterator.hasNext();) { String propName = (String) iterator.next(); String propValue = revProps.getStringValue(propName); if (SVNRevisionProperty.AUTHOR.equals(propName)) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.CREATOR_DISPLAY_NAME.getName(), propValue, null, false, true, xmlBuffer); } else if (SVNRevisionProperty.DATE.equals(propName)) { SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "date", propValue, null, false, true, xmlBuffer); } else if (SVNRevisionProperty.LOG.equals(propName)) { String comment = SVNEncodingUtil.fuzzyEscape(propValue); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.COMMENT.getName(), comment, null, false, true, xmlBuffer); } else { noCustomProperties = false; String encodedPropName = SVNEncodingUtil.xmlEncodeCDATA(propName, false); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "revprop", propValue, NAME_ATTR, encodedPropName, false, true, xmlBuffer); } } if (noCustomProperties) { SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "no-custom-revprops", SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, xmlBuffer); } if (logEntry.hasChildren()) { SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "has-children", SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, xmlBuffer); increaseDepth(); } write(xmlBuffer); if (logEntry.getChangedPaths() != null) { for (Iterator iterator = logEntry.getChangedPaths().entrySet().iterator(); iterator.hasNext();) { Map.Entry pathEntry = (Map.Entry) iterator.next(); String path = (String) pathEntry.getKey(); SVNLogEntryPath logEntryPath = (SVNLogEntryPath) pathEntry.getValue(); addChangedPathTag(path, logEntryPath); } } xmlBuffer = SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "log-item", null); write(xmlBuffer); } private void addChangedPathTag(String path, SVNLogEntryPath logEntryPath) throws SVNException { StringBuffer xmlBuffer = new StringBuffer(); switch (logEntryPath.getType()) { case SVNLogEntryPath.TYPE_ADDED: if (logEntryPath.getCopyPath() != null && SVNRevision.isValidRevisionNumber(logEntryPath.getCopyRevision())) { Map attrs = new SVNHashMap(); attrs.put(COPYFROM_PATH_ATTR, logEntryPath.getCopyPath()); attrs.put(COPYFROM_REVISION_ATTR, String.valueOf(logEntryPath.getCopyRevision())); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "added-path", path, attrs, xmlBuffer); } else { SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "added-path", path, xmlBuffer); } break; case SVNLogEntryPath.TYPE_REPLACED: Map attrs = null; if (logEntryPath.getCopyPath() != null && SVNRevision.isValidRevisionNumber(logEntryPath.getCopyRevision())) { attrs = new SVNHashMap(); attrs.put(COPYFROM_PATH_ATTR, logEntryPath.getCopyPath()); attrs.put(COPYFROM_REVISION_ATTR, String.valueOf(logEntryPath.getCopyRevision())); } SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "replaced-path", path, attrs, xmlBuffer); break; case SVNLogEntryPath.TYPE_MODIFIED: SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "modified-path", path, xmlBuffer); break; case SVNLogEntryPath.TYPE_DELETED: SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "deleted-path", path, xmlBuffer); break; default: break; } write(xmlBuffer); } } DAVLogRequest.java000066400000000000000000000210151177510526000357460ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVLogRequest extends DAVRequest { private static final DAVElement DISCOVER_CHANGED_PATHS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "discover-changed-paths"); private static final DAVElement INCLUDE_MERGED_REVISIONS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "include-merged-revisions"); private static final DAVElement STRICT_NODE_HISTORY = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "strict-node-history"); private static final DAVElement OMIT_LOG_TEXT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "omit-log-text"); private static final DAVElement LIMIT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "limit"); private static final DAVElement ALL_REVPROPS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "all-revprops"); private static final DAVElement REVPROP = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "revprop"); private static final String[] DEFAULT_REVISION_PROPERTIES = new String[]{ SVNRevisionProperty.AUTHOR, SVNRevisionProperty.DATE, SVNRevisionProperty.LOG }; private boolean myDiscoverChangedPaths = false; private boolean myStrictNodeHistory = false; private boolean myIncludeMergedRevisions = false; private boolean myOmitLogText = false; private long myStartRevision = DAVResource.INVALID_REVISION; private long myEndRevision = DAVResource.INVALID_REVISION; private long myLimit = 0; private Collection myTargetPathsCollection; private String[] myTargetPathsArray; private Collection myRevisionPropertiesCollection; private String[] myRevisionPropertiesArray; private boolean myCustomPropertyRequested = false; public boolean isDiscoverChangedPaths() { return myDiscoverChangedPaths; } private void setDiscoverChangedPaths(boolean discoverChangedPaths) { myDiscoverChangedPaths = discoverChangedPaths; } public boolean isStrictNodeHistory() { return myStrictNodeHistory; } private void setStrictNodeHistory(boolean strictNodeHistory) { myStrictNodeHistory = strictNodeHistory; } public boolean isIncludeMergedRevisions() { return myIncludeMergedRevisions; } private void setIncludeMergedRevisions(boolean includeMergedRevisions) { myIncludeMergedRevisions = includeMergedRevisions; } public boolean isOmitLogText() { return myOmitLogText; } private void setOmitLogText(boolean omitLogText) { myOmitLogText = omitLogText; } public long getStartRevision() { return myStartRevision; } private void setStartRevision(long startRevision) { myStartRevision = startRevision; } public long getEndRevision() { return myEndRevision; } private void setEndRevision(long endRevision) { myEndRevision = endRevision; } public long getLimit() { return myLimit; } private void setLimit(long limit) { myLimit = limit; } public String[] getTargetPaths() { if (myTargetPathsArray == null && myTargetPathsCollection != null) { myTargetPathsArray = (String[]) myTargetPathsCollection.toArray(new String[myTargetPathsCollection.size()]); } return myTargetPathsArray; } private void addTargetPaths(Collection targetPaths) { if (myTargetPathsCollection == null) { myTargetPathsCollection = new LinkedList(); } myTargetPathsCollection.addAll(targetPaths); } public String[] getRevisionProperties() { if (myRevisionPropertiesArray == null && myRevisionPropertiesCollection != null) { myRevisionPropertiesArray = (String[]) myRevisionPropertiesCollection.toArray(new String[myRevisionPropertiesCollection.size()]); } return myRevisionPropertiesArray; } private void addRevisionProperties(Collection revisionProperties) { if (myRevisionPropertiesCollection == null) { myRevisionPropertiesCollection = new LinkedList(); } myRevisionPropertiesCollection.addAll(revisionProperties); } private void setRevisionProperties(String[] revisionProperties) { myRevisionPropertiesArray = revisionProperties; } public boolean isCustomPropertyRequested() { return myCustomPropertyRequested; } private void setCustomPropertyRequested(boolean customPropertyRequested) { myCustomPropertyRequested = customPropertyRequested; } protected void init() throws SVNException { boolean revisionPropertyRequested = false; List children = getRootElement().getChildren(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { DAVElementProperty property = (DAVElementProperty) iterator.next(); DAVElement element = property.getName(); if (element == DISCOVER_CHANGED_PATHS) { setDiscoverChangedPaths(true); } else if (element == STRICT_NODE_HISTORY) { setStrictNodeHistory(true); } else if (element == INCLUDE_MERGED_REVISIONS) { setIncludeMergedRevisions(true); } else if (element == OMIT_LOG_TEXT) { setOmitLogText(true); } else if (element == DAVElement.START_REVISION) { String revisionString = property.getFirstValue(true); try { setStartRevision(Long.parseLong(revisionString)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (element == DAVElement.END_REVISION) { String revisionString = property.getFirstValue(true); try { setEndRevision(Long.parseLong(revisionString)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (element == LIMIT) { String limitString = property.getFirstValue(true); setLimit(Integer.parseInt(limitString)); } else if (element == DAVElement.PATH) { Collection paths = property.getValues(); if (paths != null) { addTargetPaths(paths); } } else if (element == ALL_REVPROPS) { setCustomPropertyRequested(true); revisionPropertyRequested = true; } else if (element == REVPROP) { Collection properties = property.getValues(); addRevisionProperties(properties); setCustomPropertyRequested(containsCustomProperty(properties)); revisionPropertyRequested = true; } } if (!revisionPropertyRequested) { setRevisionProperties(DEFAULT_REVISION_PROPERTIES); } } private boolean containsCustomProperty(Collection requestedProperties) { for (Iterator iterator = requestedProperties.iterator(); iterator.hasNext();) { String property = (String) iterator.next(); if (!SVNRevisionProperty.AUTHOR.equals(property) && !SVNRevisionProperty.DATE.equals(property) && !SVNRevisionProperty.LOG.equals(property)) { return true; } } return false; } } DAVMakeActivityHandler.java000066400000000000000000000061401177510526000375460ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVServletUtil; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVMakeActivityHandler extends ServletDAVHandler { private FSFS myFSFS; public DAVMakeActivityHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } public void execute() throws SVNException { DAVResource resource = getRequestedDAVResource(false, false); FSRepository repos = (FSRepository) resource.getRepository(); myFSFS = repos.getFSFS(); readInput(true); if (resource.exists()) { throw new DAVException("", HttpServletResponse.SC_CONFLICT, SVNLogType.NETWORK); } if (!resource.canBeActivity()) { throw new DAVException("", HttpServletResponse.SC_FORBIDDEN, SVNLogType.NETWORK); } try { makeActivity(resource); } catch (DAVException dave) { throw new DAVException("Could not create activity {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getURI()) }, dave.getResponseCode(), null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } setResponseHeader(CACHE_CONTROL_HEADER, CACHE_CONTROL_VALUE); handleDAVCreated(resource.getResourceURI().getURI(), "Activity", false); } protected DAVRequest getDAVRequest() { return null; } private void makeActivity(DAVResource resource) throws DAVException { FSTransactionInfo txnInfo = DAVServletUtil.createActivity(resource, myFSFS); DAVServletUtil.storeActivity(resource, txnInfo.getTxnId()); resource.setExists(true); resource.setTxnName(txnInfo.getTxnId()); } } DAVMakeCollectionHandler.java000066400000000000000000000117541177510526000400540ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPHeader; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceState; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVMakeCollectionHandler extends ServletDAVHandler { protected DAVMakeCollectionHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); } public void execute() throws SVNException { int status = processMkColBody(); if (status != HttpServletResponse.SC_OK) { sendError(status, null); return; } DAVResource resource = getRequestedDAVResource(false, false); if (resource.exists()) { sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, null); return; } DAVResourceState resourceState = getResourceState(resource); validateRequest(resource, DAVDepth.DEPTH_ZERO, resourceState == DAVResourceState.NULL ? DAV_VALIDATE_PARENT : DAV_VALIDATE_RESOURCE, null, null, null); DAVException err1 = null; DAVException err2 = null; DAVAutoVersionInfo avInfo = autoCheckOut(resource, true); resource.setCollection(true); try { createdCollection(resource); } catch (DAVException dave) { err1 = dave; } try { autoCheckIn(resource, err1 != null, false, avInfo); } catch (DAVException dave) { err2 = dave; } if (err1 != null) { throw err1; } if (err2 != null) { err1 = new DAVException("The MKCOL was successful, but there was a problem opening the lock database which prevents inheriting locks from the parent resources.", err2.getResponseCode(), err2, 0); } DAVLockInfoProvider lockProvider = null; try { lockProvider = DAVLockInfoProvider.createLockInfoProvider(this, false); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The MKCOL was successful, but there was a problem opening the lock database which prevents inheriting locks from the parent resources.", null); } notifyCreated(resource, lockProvider, resourceState, DAVDepth.DEPTH_ZERO); handleDAVCreated(null, "Collection", false); } protected DAVRequest getDAVRequest() { return null; } private int processMkColBody() throws SVNException { String transferEncoding = getRequestHeader(HTTPHeader.TRANSFER_ENCODING_HEADER); String contentLength = getRequestHeader(HTTPHeader.CONTENT_LENGTH_HEADER); boolean readChunked = false; int remaining = 0; if (transferEncoding != null) { if (!transferEncoding.equalsIgnoreCase("chunked")) { //throw new DAVException("Unknown Transfer-Encoding ", new Object[] { transferEncoding }, HttpServletResponse.SC_NOT_IMPLEMENTED, 0); return HttpServletResponse.SC_NOT_IMPLEMENTED; } readChunked = true; } else if (contentLength != null) { try { remaining = Integer.parseInt(contentLength.trim()); } catch (NumberFormatException nfe) { //throw new DAVException("Invalid Content-Length {0}", new Object[] { contentLength }, HttpServletResponse.SC_BAD_REQUEST, 0); return HttpServletResponse.SC_BAD_REQUEST; } } if (readChunked || remaining > 0) { //throw new DAVException(DAVServlet.getStatusLine(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, 0); return HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE; } readInput(true); return HttpServletResponse.SC_OK; } } DAVMergeHandler.java000066400000000000000000000503401177510526000362140ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSCommitter; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSPathChange; import org.tmatesoft.svn.core.internal.io.fs.FSPathChangeKind; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionRoot; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceKind; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; import org.tmatesoft.svn.core.internal.server.dav.DAVServletUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVMergeHandler extends ServletDAVHandler { private DAVMergeRequest myDAVRequest; protected DAVMergeHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); } public void execute() throws SVNException { long readLength = readInput(false); if (readLength <= 0) { getMergeRequest().invalidXMLRoot(); } DAVMergeRequest requestXMLObject = getMergeRequest(); DAVElementProperty rootElement = requestXMLObject.getRoot(); DAVElementProperty sourceElement = rootElement.getChild(DAVElement.SOURCE); if (sourceElement == null) { throw new DAVException("The DAV:merge element must contain a DAV:source element.", HttpServletResponse.SC_BAD_REQUEST, 0); } DAVElementProperty hrefElement = sourceElement.getChild(DAVElement.HREF); if (hrefElement == null) { throw new DAVException("The DAV:source element must contain a DAV:href element.", HttpServletResponse.SC_BAD_REQUEST, 0); } String source = hrefElement.getFirstValue(false); URI uri = null; try { uri = DAVServletUtil.lookUpURI(source, getRequest(), false); } catch (DAVException dave) { if (dave.getResponseCode() == HttpServletResponse.SC_BAD_REQUEST) { throw dave; } response(dave.getMessage(), DAVServlet.getStatusLine(dave.getResponseCode()), dave.getResponseCode()); } String path = uri.getPath(); DAVRepositoryManager manager = getRepositoryManager(); String resourceContext = manager.getResourceContext(); if (!path.startsWith(resourceContext)) { throw new DAVException("Destination url starts with a wrong context", HttpServletResponse.SC_BAD_REQUEST, 0); } //TODO: cut away the servlet context part path = path.substring(resourceContext.length()); DAVResource srcResource = getRequestedDAVResource(false, false, path); //NOTE: for now this all are no-ops, just commented them for a while //boolean noAutoMerge = rootElement.hasChild(DAVElement.NO_AUTO_MERGE); //boolean noCheckOut = rootElement.hasChild(DAVElement.NO_CHECKOUT); //DAVElementProperty propElement = rootElement.getChild(DAVElement.PROP); DAVResource resource = getRequestedDAVResource(false, false); if (!resource.exists()) { sendError(HttpServletResponse.SC_NOT_FOUND, null); return; } setResponseHeader(CACHE_CONTROL_HEADER, CACHE_CONTROL_VALUE); String response = null; try { response = merge(resource, srcResource); } catch (DAVException dave) { throw new DAVException("Could not MERGE resource \"{0}\" into \"{1}\".", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(source), SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, dave.getResponseCode(), null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } try { setResponseContentLength(response.getBytes(UTF8_ENCODING).length); } catch (UnsupportedEncodingException e) { } try { getResponseWriter().write(response); } catch (IOException ioe) { throw new DAVException(ioe.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, SVNErrorCode.IO_ERROR.getCode()); } } protected DAVRequest getDAVRequest() { return getMergeRequest(); } private String merge(DAVResource targetResource, DAVResource sourceResource) throws DAVException { boolean disableMergeResponse = false; if (sourceResource.getType() != DAVResourceType.ACTIVITY) { throw new DAVException("MERGE can only be performed using an activity as the source [at this time].", null, HttpServletResponse.SC_METHOD_NOT_ALLOWED, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.INCORRECT_PARAMS.getCode(), null); } Map locks = parseLocks(getMergeRequest().getRootElement(), targetResource.getResourceURI().getPath()); if (!locks.isEmpty()) { sourceResource.setLockTokens(locks.values()); } FSFS fsfs = sourceResource.getFSFS(); String txnName = sourceResource.getTxnName(); FSTransactionInfo txn = DAVServletUtil.openTxn(fsfs, txnName); FSTransactionRoot txnRoot = null; try { txnRoot = fsfs.createTransactionRoot(txn); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open a (transaction) root in the repository", null); } FSCommitter committer = getCommitter(sourceResource.getFSFS(), txnRoot, txn, sourceResource.getLockTokens(), sourceResource.getUserName()); StringBuffer buffer = new StringBuffer(); SVNErrorMessage[] postCommitHookErr = new SVNErrorMessage[1]; String postCommitErrMessage = null; long newRev = -1; try { newRev = committer.commitTxn(true, true, postCommitHookErr, buffer); } catch (SVNException svne) { if (postCommitHookErr[0] == null) { try { FSCommitter.abortTransaction(fsfs, txnName); } catch (SVNException svne1) { // } if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.FS_CONFLICT) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_CONFLICT, "A conflict occurred during the MERGE processing. The problem occurred with the \"{0}\" resource.", new Object[] { buffer.toString() }); } throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_CONFLICT, "An error occurred while committing the transaction.", null); } } if (postCommitHookErr[0] != null) { SVNErrorMessage childErr = postCommitHookErr[0].getChildErrorMessage(); if (childErr != null && childErr.getMessage() != null) { postCommitErrMessage = childErr.getMessage(); } } //TODO: maybe add logging here DAVServletUtil.storeActivity(sourceResource, ""); String clientOptions = sourceResource.getClientOptions(); if (clientOptions != null) { if (clientOptions.indexOf(DAVLockInfoProvider.RELEASE_LOCKS_OPTION) != -1 && !locks.isEmpty()) { for (Iterator locksIter = locks.keySet().iterator(); locksIter.hasNext();) { String path = (String) locksIter.next(); String lockToken = (String) locks.get(path); try { fsfs.unlockPath(path, lockToken, sourceResource.getUserName(), false, true); } catch (SVNException svne) { // TODO: ignore exceptions. maybe add logging } } } if (clientOptions.indexOf(DAVLockInfoProvider.NO_MERGE_RESPONSE) != -1) { disableMergeResponse = true; } } return response(fsfs, newRev, postCommitErrMessage, disableMergeResponse); } private String response(FSFS fsfs, long newRev, String postCommitErr, boolean disableMergeResponse) throws DAVException { FSRevisionRoot root = null; try { root = fsfs.createRevisionRoot(newRev); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open the FS root for the revision just committed.", null); } String vcc = DAVPathUtil.buildURI(getRepositoryManager().getResourceContext(), DAVResourceKind.VCC, -1, null, false); StringBuffer buffer = new StringBuffer(); Map prefixMap = new HashMap(); Collection namespaces = new LinkedList(); namespaces.add(DAVElement.DAV_NAMESPACE); prefixMap.put(DAVElement.DAV_NAMESPACE, SVNXMLUtil.DAV_NAMESPACE_PREFIX); String postCommitErrElement = null; if (postCommitErr != null) { namespaces.add(DAVElement.SVN_NAMESPACE); prefixMap.put(DAVElement.SVN_NAMESPACE, SVNXMLUtil.SVN_NAMESPACE_PREFIX); SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, DAVElement.POST_COMMIT_ERROR.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append(postCommitErr); SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, DAVElement.POST_COMMIT_ERROR.getName(), buffer); postCommitErrElement = buffer.toString(); buffer.delete(0, buffer.length()); } else { postCommitErrElement = ""; } String creationDate = null; String creatorDisplayName = null; try { SVNProperties revProps = fsfs.getRevisionProperties(newRev); creationDate = revProps.getStringValue(SVNRevisionProperty.DATE); creatorDisplayName = revProps.getStringValue(SVNRevisionProperty.AUTHOR); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not get author of newest revision", null); } SVNXMLUtil.addXMLHeader(buffer); SVNXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.MERGE_RESPONSE.getName(), namespaces, prefixMap, null, buffer, true); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.UPDATE_SET.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), vcc, null, true, true, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESOURCE_TYPE.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.BASELINE.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESOURCE_TYPE.getName(), buffer); buffer.append(postCommitErrElement); buffer.append('\n'); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.VERSION_NAME.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append(newRev); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.VERSION_NAME.getName(), buffer); if (creationDate != null ) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.CREATION_DATE.getName(), creationDate, null, true, true, buffer); } if (creatorDisplayName != null ) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.CREATOR_DISPLAY_NAME.getName(), creatorDisplayName, null, true, true, buffer); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append("HTTP/1.1 200 OK"); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE.getName(), buffer); if (!disableMergeResponse) { try { doResources(root, buffer); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error constructing resource list.", null); } } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.UPDATE_SET.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.MERGE_RESPONSE.getName(), buffer); return buffer.toString(); } private void doResources(FSRevisionRoot root, StringBuffer buffer) throws SVNException { Map changedPaths = root.getChangedPaths(); Map sentPaths = new HashMap(); for (Iterator pathsIter = changedPaths.keySet().iterator(); pathsIter.hasNext();) { String path = (String) pathsIter.next(); FSPathChange pathChange = (FSPathChange) changedPaths.get(path); boolean sendSelf = false; boolean sendParent = false; FSPathChangeKind changeKind = pathChange.getChangeKind(); if (changeKind == FSPathChangeKind.FS_PATH_CHANGE_DELETE) { sendSelf = false; sendParent = true; } else if (changeKind == FSPathChangeKind.FS_PATH_CHANGE_ADD || changeKind == FSPathChangeKind.FS_PATH_CHANGE_REPLACE) { sendSelf = true; sendParent = true; } else { sendSelf = true; sendParent = false; } if (sendSelf) { if (!sentPaths.containsKey(path)) { SVNNodeKind pathKind = root.checkNodeKind(path); sendResponse(root, path, pathKind == SVNNodeKind.DIR, buffer); sentPaths.put(path, path); } } if (sendParent) { String parentPath = SVNPathUtil.removeTail(path); if (!sentPaths.containsKey(parentPath)) { sendResponse(root, parentPath, true, buffer); sentPaths.put(parentPath, parentPath); } } } } private void sendResponse(FSRevisionRoot root, String path, boolean isDir, StringBuffer buffer) { String context = getRepositoryManager().getResourceContext(); String href = DAVPathUtil.buildURI(context, DAVResourceKind.PUBLIC, -1, path, false); long revToUse = DAVServletUtil.getSafeCreatedRevision(root, path); String vsnURL = DAVPathUtil.buildURI(context, DAVResourceKind.VERSION, revToUse, path, false); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), href, null, true, true, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); if (isDir) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESOURCE_TYPE.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.COLLECTION.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESOURCE_TYPE.getName(), buffer); } else { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESOURCE_TYPE.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); } SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.CHECKED_IN.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), vsnURL, null, true, true, buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.CHECKED_IN.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append("HTTP/1.1 200 OK"); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE.getName(), buffer); } private DAVMergeRequest getMergeRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVMergeRequest(); } return myDAVRequest; } } DAVMergeInfoHandler.java000066400000000000000000000117531177510526000370350ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNMergeInfo; import org.tmatesoft.svn.core.SVNMergeRangeList; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVMergeInfoHandler extends DAVReportHandler { private static final String MERGEINFO_REPORT = "mergeinfo-report"; private DAVMergeInfoRequest myDAVRequest; private DAVReportHandler myCommonReportHandler; public DAVMergeInfoHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(repositoryManager, request, response); myCommonReportHandler = commonReportHandler; } protected DAVRequest getDAVRequest() { return getMergeInfoRequest(); } private DAVMergeInfoRequest getMergeInfoRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVMergeInfoRequest(); } return myDAVRequest; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace(null); setDAVResource(getRequestedDAVResource(false, false)); String responseBody = generateResponseBody(); try { setResponseContentLength(responseBody.getBytes(UTF8_ENCODING).length); } catch (UnsupportedEncodingException e) { } write(responseBody); } private String generateResponseBody() throws SVNException { StringBuffer xmlBuffer = new StringBuffer(); addXMLHeader(xmlBuffer, MERGEINFO_REPORT); for (int i = 0; i < getMergeInfoRequest().getTargetPaths().length; i++) { String currentPath = getMergeInfoRequest().getTargetPaths()[i]; DAVPathUtil.testCanonical(currentPath); if (currentPath.length() == 0 || currentPath.charAt(0) != '/') { getMergeInfoRequest().getTargetPaths()[i] = SVNPathUtil.append(getDAVResource().getResourceURI().getPath(), currentPath); } } //TODO: fixme - add includeDescendants parameter Map mergeInfoMap = getDAVResource().getRepository().getMergeInfo(getMergeInfoRequest().getTargetPaths(), getMergeInfoRequest().getRevision(), getMergeInfoRequest().getInherit(), false); if (mergeInfoMap != null && !mergeInfoMap.isEmpty()) { for (Iterator iterator = mergeInfoMap.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String path = (String) entry.getKey(); SVNMergeInfo mergeInfo = (SVNMergeInfo) entry.getValue(); addMergeInfo(path, mergeInfo, xmlBuffer); } } addXMLFooter(xmlBuffer, MERGEINFO_REPORT); return xmlBuffer.toString(); } private void addMergeInfo(String path, SVNMergeInfo mergeInfo, StringBuffer xmlBuffer) { SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "mergeinfo-item", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "mergeinfo-path", path, xmlBuffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "mergeinfo-info", addSourcePathes(mergeInfo), xmlBuffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "mergeinfo-item", xmlBuffer); } private String addSourcePathes(SVNMergeInfo mergeInfo) { StringBuffer result = new StringBuffer(); for (Iterator iterator = mergeInfo.getMergeSourcesToMergeLists().entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String sourcePath = (String) entry.getKey(); SVNMergeRangeList rangeList = (SVNMergeRangeList) entry.getValue(); result.append(sourcePath); result.append(":"); result.append(rangeList.toString()); if (iterator.hasNext()) { result.append('\n'); } } return result.toString(); } } DAVMergeInfoRequest.java000066400000000000000000000072051177510526000371050ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNMergeInfoInheritance; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVMergeInfoRequest extends DAVRequest { private static final DAVElement INHERIT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "inherit"); long myRevision = DAVResource.INVALID_REVISION; SVNMergeInfoInheritance myInherit = SVNMergeInfoInheritance.EXPLICIT; String[] myTargetPaths = null; public long getRevision() { return myRevision; } private void setRevision(long revision) { myRevision = revision; } public SVNMergeInfoInheritance getInherit() { return myInherit; } private void setInherit(SVNMergeInfoInheritance inherit) { myInherit = inherit; } public String[] getTargetPaths() { return myTargetPaths; } private void setTargetPaths(String[] targetPaths) { myTargetPaths = targetPaths; } protected void init() throws SVNException { List children = getRootElement().getChildren(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { DAVElementProperty property = (DAVElementProperty) iterator.next(); DAVElement element = property.getName(); if (element == DAVElement.REVISION) { try { setRevision(Long.parseLong(property.getFirstValue(true))); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (element == INHERIT) { setInherit(parseInheritance(property.getFirstValue(true))); if (getInherit() == null) { invalidXML(); } } else if (element == DAVElement.PATH) { Collection paths = property.getValues(); String[] targetPaths = new String[paths.size()]; targetPaths = (String[]) paths.toArray(targetPaths); setTargetPaths(targetPaths); } } } private SVNMergeInfoInheritance parseInheritance(String inheritance) { if (SVNMergeInfoInheritance.EXPLICIT.toString().equals(inheritance)) { return SVNMergeInfoInheritance.EXPLICIT; } else if (SVNMergeInfoInheritance.INHERITED.toString().equals(inheritance)) { return SVNMergeInfoInheritance.INHERITED; } else if (SVNMergeInfoInheritance.NEAREST_ANCESTOR.toString().equals(inheritance)) { return SVNMergeInfoInheritance.NEAREST_ANCESTOR; } return null; } } DAVMergeRequest.java000066400000000000000000000030221177510526000362620ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVException; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVMergeRequest extends DAVRequest { private static final DAVElement MERGE = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "merge"); protected void init() throws SVNException { if (getRoot().getName() != MERGE) { invalidXMLRoot(); } } protected void invalidXMLRoot() throws SVNException { throw new DAVException("The request body must be present and must be a DAV:merge element.", HttpServletResponse.SC_BAD_REQUEST, 0); } protected DAVElementProperty getRoot() throws SVNException { if (getRootElement() == null) { invalidXMLRoot(); } return getRootElement(); } } DAVOptionsHandler.java000066400000000000000000000350301177510526000366070ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceKind; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.Attributes; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVOptionsHandler extends ServletDAVHandler { private static final DAVElement OPTIONS = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "options"); private static final DAVElement ACTIVITY_COLLECTION_SET = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "activity-collection-set"); private static final DAVElement SUPPORTED_METHOD_SET = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "supported-method-set"); private static final DAVElement SUPPORTED_METHOD = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "supported-method"); private static final DAVElement SUPPORTED_LIVE_PROPERTY_SET = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "supported-live-property-set"); private static final DAVElement SUPPORTED_LIVE_PROPERTY = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "supported-live-property"); private static final DAVElement SUPPORTED_REPORT_SET = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "supported-report-set"); private static final DAVElement SUPPORTED_REPORT = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "supported-report"); private static final String DAV_HEADER = "DAV"; private static final String DAV_LEVEL = "1,2"; private static final String VERSION_OPTIONS_FIRST_PART = "version-control,checkout,working-resource"; private static final String VERSION_OPTIONS_SECOND_PART = "merge,baseline,activity,version-controlled-collection"; private static final String MS_AUTHOR_VIA_HEADER = "MS-Author-Via"; private static final String ALLOW_HEADER = "Allow"; private DAVOptionsRequest myDAVRequest; public DAVOptionsHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); } protected DAVRequest getDAVRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVOptionsRequest(); } return myDAVRequest; } private DAVOptionsRequest getOptionsRequest() { return (DAVOptionsRequest) getDAVRequest(); } public void execute() throws SVNException { SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "in execute() of DAVOptiondsHandler"); readInput(false); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "read input"); DAVResource resource = getRequestedDAVResource(false, false); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "got resource"); Collection supportedMethods = getSupportedMethods(resource); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "got supported methods"); StringBuffer body = new StringBuffer(); generateOptionsResponse(resource, supportedMethods, body); String responseBody = body.toString(); try { setResponseContentLength(responseBody.getBytes(UTF8_ENCODING).length); } catch (UnsupportedEncodingException e) { setResponseContentLength(responseBody.getBytes().length); } setDefaultResponseHeaders(); setResponseHeaders(supportedMethods); setResponseContentType(DEFAULT_XML_CONTENT_TYPE); setResponseStatus(HttpServletResponse.SC_OK); try { getResponseWriter().write(responseBody); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } protected void startElement(DAVElement parent, DAVElement element, Attributes attrs) throws SVNException { if (parent == null && element != OPTIONS) { invalidXML(); } else if (parent == OPTIONS && element == ACTIVITY_COLLECTION_SET) { getOptionsRequest().setActivitySetRequest(true); } else if (parent == SUPPORTED_METHOD_SET && element == SUPPORTED_METHOD) { String requestedMethodName = attrs.getValue(DAVElement.DAV_NAMESPACE, NAME_ATTR); if (requestedMethodName == null || getOptionsRequest().getRequestedMethods() == null) { invalidXML(); } getOptionsRequest().getRequestedMethods().add(requestedMethodName); } else if (parent == SUPPORTED_REPORT_SET && element == SUPPORTED_REPORT) { String requestedReportName = attrs.getValue(DAVElement.DAV_NAMESPACE, NAME_ATTR); String requestedReportNamespace = attrs.getValue(DAVElement.DAV_NAMESPACE, NAMESPACE_ATTR); if (requestedReportName == null || getOptionsRequest().getRequestedReports() == null) { invalidXML(); } if (requestedReportNamespace == null) { requestedReportNamespace = DAVElement.SVN_NAMESPACE; } getOptionsRequest().getRequestedReports().add(DAVElement.getElement(requestedReportNamespace, requestedReportName)); } else if (parent == SUPPORTED_LIVE_PROPERTY_SET && element == SUPPORTED_LIVE_PROPERTY) { String requestedLivePropertyName = attrs.getValue(DAVElement.DAV_NAMESPACE, NAME_ATTR); String requestedLivePropertyNamespace = attrs.getValue(DAVElement.DAV_NAMESPACE, NAMESPACE_ATTR); if (requestedLivePropertyName == null || getOptionsRequest().getRequestedLiveProperties() == null) { invalidXML(); } if (requestedLivePropertyNamespace == null) { requestedLivePropertyNamespace = DAVElement.DAV_NAMESPACE; } getOptionsRequest().getRequestedLiveProperties().add(DAVElement.getElement(requestedLivePropertyNamespace, requestedLivePropertyName)); } } protected void endElement(DAVElement parent, DAVElement element, StringBuffer cdata) throws SVNException { } private static Collection getSupportedMethods(DAVResource resource) throws SVNException { //TODO: when work with locks will be implemented, we need to check resource state: LOCK_NULL, EXIST, NULL. Collection supportedMethods = new ArrayList(); supportedMethods.add(DAVHandlerFactory.METHOD_OPTIONS); if (resource.exists()) { supportedMethods.add(DAVHandlerFactory.METHOD_GET); supportedMethods.add(DAVHandlerFactory.METHOD_HEAD); supportedMethods.add(DAVHandlerFactory.METHOD_POST); supportedMethods.add(DAVHandlerFactory.METHOD_DELETE); supportedMethods.add(DAVHandlerFactory.METHOD_TRACE); supportedMethods.add(DAVHandlerFactory.METHOD_PROPFIND); supportedMethods.add(DAVHandlerFactory.METHOD_PROPPATCH); supportedMethods.add(DAVHandlerFactory.METHOD_MOVE); supportedMethods.add(DAVHandlerFactory.METHOD_COPY); supportedMethods.add(DAVHandlerFactory.METHOD_LOCK); supportedMethods.add(DAVHandlerFactory.METHOD_UNLOCK); if (!resource.isCollection()) { supportedMethods.add(DAVHandlerFactory.METHOD_PUT); } } //TODO: native svn checks if resource is auto checked out. if (resource.getResourceURI().getType() == DAVResourceType.ACTIVITY && !resource.exists()) { supportedMethods.add(DAVHandlerFactory.METHOD_MKACTIVITY); } else if (resource.getResourceURI().isWorking()) { supportedMethods.add(DAVHandlerFactory.METHOD_CHECKIN); } else { supportedMethods.add(DAVHandlerFactory.METHOD_CHECKOUT); } return supportedMethods; } private void setResponseHeaders(Collection supportedMethods) { //MSFT Web Folders chokes if length of DAV header value > 63 characters! (c) Subversion. setResponseHeader(DAV_HEADER, DAV_LEVEL); addResponseHeader(DAV_HEADER, VERSION_OPTIONS_FIRST_PART); addResponseHeader(DAV_HEADER, VERSION_OPTIONS_SECOND_PART); addResponseHeader(DAV_HEADER, DAVElement.DEPTH_OPTION); addResponseHeader(DAV_HEADER, DAVElement.LOG_REVPROPS_OPTION); addResponseHeader(DAV_HEADER, DAVElement.PARTIAL_REPLAY_OPTION); addResponseHeader(DAV_HEADER, DAVElement.MERGE_INFO_OPTION); setResponseHeader(MS_AUTHOR_VIA_HEADER, DAV_HEADER); setResponseHeader(ALLOW_HEADER, generateAllowHeaderValue(supportedMethods)); } private String generateAllowHeaderValue(Collection supportedMethods) { StringBuffer allowHeaderBuffer = new StringBuffer(); for (Iterator iterator = supportedMethods.iterator(); iterator.hasNext();) { allowHeaderBuffer.append(iterator.next()); allowHeaderBuffer.append(iterator.hasNext() ? "," : ""); } return allowHeaderBuffer.toString(); } private void generateOptionsResponse(DAVResource resource, Collection supportedMethods, StringBuffer xmlBuffer) throws SVNException { if (!getOptionsRequest().isEmpty()) { SVNXMLUtil.addXMLHeader(xmlBuffer); DAVXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "options-response", null, xmlBuffer, false); if (getOptionsRequest().isActivitySetRequest()) { generateActivityCollectionSet(resource, xmlBuffer); } else if (getOptionsRequest().isSupportedLivePropertiesRequest()) { generateSupportedLivePropertySet(resource, xmlBuffer); } else if (getOptionsRequest().isSupportedMethodsRequest()) { generateSupportedMethodSet(supportedMethods, xmlBuffer); } else if (getOptionsRequest().isSupportedReportsRequest()) { generateSupportedReportSet(resource, xmlBuffer); } SVNXMLUtil.addXMLFooter(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "options-response", xmlBuffer); } } private void generateActivityCollectionSet(DAVResource resource, StringBuffer xmlBuffer) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "activity-collection-set", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); String uri = DAVPathUtil.buildURI(resource.getResourceURI().getContext(), DAVResourceKind.ACT_COLLECTION, 0, null, false); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "href", uri, xmlBuffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "activity-collection-set", xmlBuffer); } private void generateSupportedLivePropertySet(DAVResource resource, StringBuffer xmlBuffer) throws SVNException { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-live-property-set", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); Collection supportedLiveProperties = getSupportedLiveProperties(resource, null); generateSupportedElementSet(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-live-property", supportedLiveProperties, getOptionsRequest().getRequestedLiveProperties(), xmlBuffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-live-property-set", xmlBuffer); } private void generateSupportedMethodSet(Collection supportedMethods, StringBuffer xmlBuffer) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-method-set", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); generateSupportedElementSet(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-method", supportedMethods, getOptionsRequest().getRequestedMethods(), xmlBuffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-method-set", xmlBuffer); } private void generateSupportedReportSet(DAVResource resource, StringBuffer xmlBuffer) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-report-set", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); if (resource.getResourceURI().getType() == DAVResourceType.REGULAR) { generateSupportedElementSet(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-report", REPORT_ELEMENTS, getOptionsRequest().getRequestedReports(), xmlBuffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "supported-report-set", xmlBuffer); } } private void generateSupportedElementSet(String prefix, String tagName, Collection supportedElements, Collection requestedElements, StringBuffer xmlBuffer) { for (Iterator iterator = supportedElements.iterator(); iterator.hasNext();) { Object item = iterator.next(); if (requestedElements.isEmpty() || requestedElements.contains(item)) { Map attrs = new SVNHashMap(); if (item instanceof DAVElement) { DAVElement currentElement = (DAVElement) item; attrs.put(NAME_ATTR, currentElement.getNamespace()); attrs.put(NAMESPACE_ATTR, currentElement.getName()); } else if (item instanceof String) { String currentName = (String) item; attrs.put(NAME_ATTR, currentName); } SVNXMLUtil.openXMLTag(prefix, tagName, SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, xmlBuffer); } } } } DAVOptionsRequest.java000066400000000000000000000045631177510526000366710ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.ArrayList; import java.util.Collection; import org.tmatesoft.svn.core.SVNException; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVOptionsRequest extends DAVRequest { private boolean myIsActivitySetRequest = false; private Collection myRequestedMethods; private Collection myRequestedReports; private Collection myRequestedLiveProperties; public DAVOptionsRequest() { super(); } protected void init() throws SVNException { } public boolean isEmpty() { return !(isActivitySetRequest() || isSupportedLivePropertiesRequest() || isSupportedMethodsRequest() || isSupportedMethodsRequest()); } public boolean isActivitySetRequest() { return myIsActivitySetRequest; } public void setActivitySetRequest(boolean isActivitySetRequest) { myIsActivitySetRequest = isActivitySetRequest; } public boolean isSupportedMethodsRequest() { return myRequestedMethods != null; } public boolean isSupportedLivePropertiesRequest() { return myRequestedLiveProperties != null; } public boolean isSupportedReportsRequest() { return myRequestedReports != null; } public Collection getRequestedMethods() { if (myRequestedMethods == null) { myRequestedMethods = new ArrayList(); } return myRequestedMethods; } public Collection getRequestedLiveProperties() { if (myRequestedLiveProperties == null) { myRequestedLiveProperties = new ArrayList(); } return myRequestedLiveProperties; } public Collection getRequestedReports() { if (myRequestedReports == null) { myRequestedReports = new ArrayList(); } return myRequestedReports; } } DAVPropPatchHandler.java000066400000000000000000000405051177510526000370570ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVErrorCode; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVPropPatchHandler extends ServletDAVHandler { private DAVPropPatchRequest myDAVRequest; protected DAVPropPatchHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); } public void execute() throws SVNException { DAVResource resource = getRequestedDAVResource(false, false); if (!resource.exists()) { sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } long readLength = readInput(false); if (readLength <= 0) { getPropPatchRequest().invalidXMLRoot(); } validateRequest(resource, DAVDepth.DEPTH_ZERO, DAV_VALIDATE_RESOURCE, null, null, null); DAVAutoVersionInfo avInfo = autoCheckOut(resource, false); DAVPropertiesProvider propsProvider = null; try { propsProvider = DAVPropertiesProvider.createPropertiesProvider(resource, this); } catch (DAVException dave) { autoCheckIn(resource, true, false, avInfo); throw new DAVException("Could not open the property database for {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } boolean isFailure = false; List properties = new LinkedList(); DAVPropPatchRequest requestXMLObject = getPropPatchRequest(); DAVElementProperty rootElement = requestXMLObject.getRoot(); List childrenElements = rootElement.getChildren(); for (Iterator childrenIter = childrenElements.iterator(); childrenIter.hasNext();) { DAVElementProperty childElement = (DAVElementProperty) childrenIter.next(); DAVElement childElementName = childElement.getName(); if (!DAVElement.DAV_NAMESPACE.equals(childElementName.getNamespace()) || (childElementName != DAVPropPatchRequest.REMOVE && childElementName != DAVPropPatchRequest.SET)) { continue; } DAVElementProperty propChildrenElement = childElement.getChild(DAVElement.PROP); if (propChildrenElement == null) { autoCheckIn(resource, true, false, avInfo); SVNDebugLog.getDefaultLog().logError(SVNLogType.NETWORK, "A \"prop\" element is missing inside the propertyupdate command."); setResponseStatus(HttpServletResponse.SC_BAD_REQUEST); return; } boolean isRemove = childElementName == DAVPropPatchRequest.REMOVE; List propChildren = propChildrenElement.getChildren(); for (Iterator propsIter = propChildren.iterator(); propsIter.hasNext();) { DAVElementProperty property = (DAVElementProperty) propsIter.next(); DAVElement propertyName = property.getName(); PropertyChangeContext propContext = new PropertyChangeContext(); propContext.myIsSet = !isRemove; propContext.myProperty = property; properties.add(propContext); validateProp(propertyName, propsProvider, propContext); if (propContext.myError != null && propContext.myError.getResponseCode() >= 300) { isFailure = true; } } } String propStatText = null; DAVPropertyExecuteHandler executeHandler = new DAVPropertyExecuteHandler(propsProvider); if (!isFailure && processPropertyContextList(executeHandler, properties, true, false)) { isFailure = true; } if (isFailure) { DAVPropertyRollBackHandler rollBackHandler = new DAVPropertyRollBackHandler(propsProvider); processPropertyContextList(rollBackHandler, properties, false, true); propStatText = getFailureMessage(properties); } else { propStatText = getSuccessMessage(properties); } autoCheckIn(resource, isFailure, false, avInfo); //TODO: log propCtxt.error here later DAVPropsResult propResult = new DAVPropsResult(); propResult.addPropStatsText(propStatText); DAVResponse response = new DAVResponse(null, resource.getResourceURI().getRequestURI(), null, propResult, 0); try { DAVXMLUtil.sendMultiStatus(response, getHttpServletResponse(), SC_MULTISTATUS, getNamespaces()); } catch (IOException ioe) { throw new DAVException(ioe.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, SVNErrorCode.IO_ERROR.getCode()); } } private String getFailureMessage(List propContextList) { DAVException err424Set = null; DAVException err424Delete = null; StringBuffer buffer = new StringBuffer(); for (Iterator propsIter = propContextList.iterator(); propsIter.hasNext();) { PropertyChangeContext propContext = (PropertyChangeContext) propsIter.next(); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); DAVXMLUtil.addEmptyElement(getNamespaces(), propContext.myProperty.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), buffer); if (propContext.myError == null) { if (propContext.myIsSet) { if (err424Set == null) { err424Set = new DAVException("Attempted DAV:set operation could not be completed due to other errors.", SC_FAILED_DEPENDANCY, 0); } propContext.myError = err424Set; } else { if (err424Delete == null) { err424Delete = new DAVException("Attempted DAV:remove operation could not be completed due to other errors.", SC_FAILED_DEPENDANCY, 0); } propContext.myError = err424Delete; } } SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append("HTTP/1.1 "); buffer.append(propContext.myError.getResponseCode()); buffer.append(" (status)"); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), buffer); if (propContext.myError.getMessage() != null) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE_DESCRIPTION.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); buffer.append(propContext); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.RESPONSE_DESCRIPTION.getName(), buffer); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), buffer); } return buffer.toString(); } private String getSuccessMessage(List propContextList) { StringBuffer buffer = new StringBuffer(); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); for (Iterator propsIter = propContextList.iterator(); propsIter.hasNext();) { PropertyChangeContext propContext = (PropertyChangeContext) propsIter.next(); DAVXMLUtil.addEmptyElement(getNamespaces(), propContext.myProperty.getName(), buffer); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append("HTTP/1.1 200 OK"); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), buffer); return buffer.toString(); } private boolean processPropertyContextList(IDAVPropertyContextHandler handler, List propertyContextList, boolean stopOnError, boolean reverse) { ListIterator propContextIterator = propertyContextList.listIterator(reverse ? propertyContextList.size() : 0); for (; reverse ? propContextIterator.hasPrevious() : propContextIterator.hasNext();) { PropertyChangeContext propContext = (PropertyChangeContext) (reverse ? propContextIterator.previous() : propContextIterator.next()); handler.handleContext(propContext); if (stopOnError && propContext.myError != null && propContext.myError.getResponseCode() >= 300) { return true; } } return false; } private void validateProp(DAVElement property, DAVPropertiesProvider propsProvider, PropertyChangeContext propContext) { LivePropertySpecification livePropSpec = findLiveProperty(property); propContext.myLivePropertySpec = livePropSpec; if (!isPropertyWritable(property, livePropSpec)) { propContext.myError = new DAVException("Property is read-only.", HttpServletResponse.SC_CONFLICT, DAVErrorCode.PROP_READONLY); return; } if (livePropSpec != null && livePropSpec.isSVNSupported()) { return; } if (propsProvider.isDeferred()) { try { propsProvider.open(false); } catch (DAVException dave) { propContext.myError = dave; return; } } if (!propsProvider.isOperative()) { propContext.myError = new DAVException("Attempted to set/remove a property without a valid, open, read/write property database.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DAVErrorCode.PROP_NO_DATABASE); return; } } protected DAVRequest getDAVRequest() { return getPropPatchRequest(); } private boolean isPropertyWritable(DAVElement property, LivePropertySpecification livePropSpec) { if (livePropSpec != null) { return livePropSpec.isWritable(); } if (property == DAVElement.LOCK_DISCOVERY || property == DAVElement.SUPPORTED_LOCK) { return false; } return true; } private DAVPropPatchRequest getPropPatchRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVPropPatchRequest(); } return myDAVRequest; } private static class PropertyChangeContext { private boolean myIsSet; private DAVElementProperty myProperty; private LivePropertySpecification myLivePropertySpec; private DAVException myError; private RollBackProperty myRollBackProperty; } private static class RollBackProperty { private DAVElement myPropertyName; private SVNPropertyValue myRollBackPropertyValue; public RollBackProperty(DAVElement propertyName, SVNPropertyValue rollBackPropertyValue) { myPropertyName = propertyName; myRollBackPropertyValue = rollBackPropertyValue; } } private static interface IDAVPropertyContextHandler { public void handleContext(PropertyChangeContext propContext); } private class DAVPropertyExecuteHandler implements IDAVPropertyContextHandler { private DAVPropertiesProvider myPropsProvider; public DAVPropertyExecuteHandler(DAVPropertiesProvider propsProvider) { myPropsProvider = propsProvider; } public void handleContext(PropertyChangeContext propContext) { if (propContext.myLivePropertySpec == null) { try { SVNPropertyValue rollBackPropValue = myPropsProvider.getPropertyValue(propContext.myProperty.getName()); propContext.myRollBackProperty = new RollBackProperty(propContext.myProperty.getName(), rollBackPropValue); } catch (DAVException dave) { handleError(dave, propContext); return; } if (propContext.myIsSet) { try { myPropsProvider.storeProperty(propContext.myProperty); } catch (DAVException dave) { handleError(dave, propContext); return; } } else { try { myPropsProvider.removeProperty(propContext.myProperty.getName()); } catch (DAVException dave) { // } } } } private void handleError(DAVException dave, PropertyChangeContext propContext) { DAVException exc = new DAVException("Could not execute PROPPATCH.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, dave, DAVErrorCode.PROP_EXEC); propContext.myError = exc; } } private class DAVPropertyRollBackHandler implements IDAVPropertyContextHandler { private DAVPropertiesProvider myPropsProvider; public DAVPropertyRollBackHandler(DAVPropertiesProvider propsProvider) { myPropsProvider = propsProvider; } public void handleContext(PropertyChangeContext propContext) { if (propContext.myRollBackProperty == null) { return; } if (propContext.myLivePropertySpec == null) { try { myPropsProvider.applyRollBack(propContext.myRollBackProperty.myPropertyName, propContext.myRollBackProperty.myRollBackPropertyValue); } catch (DAVException dave) { if (propContext.myError == null) { propContext.myError = dave; } else { DAVException err = dave; while (err.getPreviousException() != null) { err = err.getPreviousException(); } err.setPreviousException(propContext.myError); propContext.myError = dave; } } } } } } DAVPropPatchRequest.java000066400000000000000000000036241177510526000371330ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVPropPatchRequest extends DAVRequest { private static final DAVElement PROPERTY_UPDATE = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "propertyupdate"); public static final DAVElement REMOVE = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "remove"); public static final DAVElement SET = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "set"); protected void init() throws SVNException { if (getRoot().getName() != PROPERTY_UPDATE) { invalidXMLRoot(); } } protected void invalidXMLRoot() throws SVNException { throw new DAVException("The request body does not contain a \"propertyupdate\" element.", null, HttpServletResponse.SC_BAD_REQUEST, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } protected DAVElementProperty getRoot() throws SVNException { if (getRootElement() == null) { invalidXMLRoot(); } return getRootElement(); } } DAVPropertiesProvider.java000066400000000000000000000363061177510526000375340ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSCommitter; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionNode; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.server.dav.DAVConfig; import org.tmatesoft.svn.core.internal.server.dav.DAVErrorCode; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceURI; import org.tmatesoft.svn.core.internal.util.SVNBase64; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.io.SVNRepository; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVPropertiesProvider { private boolean myIsDeferred; private boolean myIsOperative; private DAVResource myResource; private ServletDAVHandler myOwner; private SVNProperties myProperties; private DAVPropertiesProvider(boolean isDeferred, ServletDAVHandler owner, DAVResource resource) { myIsDeferred = isDeferred; myOwner = owner; myResource = resource; } public static DAVPropertiesProvider createPropertiesProvider(DAVResource resource, ServletDAVHandler owner) throws DAVException { DAVResourceURI resourceURI = resource.getResourceURI(); if (resourceURI.getURI() == null) { throw new DAVException("INTERNAL DESIGN ERROR: resource must define its URI.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } DAVPropertiesProvider provider = new DAVPropertiesProvider(true, owner, resource); return provider; } public void open(boolean readOnly) throws DAVException { myIsDeferred = false; try { doOpen(readOnly); } catch (DAVException dave) { throw new DAVException("Could not open the property database.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DAVErrorCode.PROP_OPENING); } } public void applyRollBack(DAVElement propName, SVNPropertyValue propValue) throws DAVException { if (propValue == null) { removeProperty(propName); return; } saveValue(propName, propValue); } public void removeProperty(DAVElement propName) throws DAVException { String reposPropName = getReposPropName(propName); if (reposPropName == null) { return; } try { FSFS fsfs = myResource.getFSFS(); if (myResource.isBaseLined()) { if (myResource.isWorking()) { FSTransactionInfo txn = myResource.getTxnInfo(); SVNProperties props = new SVNProperties(); props.put(reposPropName, (SVNPropertyValue) null); fsfs.changeTransactionProperties(txn.getTxnId(), props); } else { SVNRepository repos = myResource.getRepository(); repos.setRevisionPropertyValue(myResource.getRevision(), reposPropName, null); } } else { DAVResourceURI resourceURI = myResource.getResourceURI(); FSCommitter committer = getCommitter(); committer.changeNodeProperty(resourceURI.getPath(), reposPropName, null); } } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not remove a property", null); } myProperties = null; } public void storeProperty(DAVElementProperty property) throws DAVException { DAVElement propName = property.getName(); String propValue = property.getFirstValue(false); String reposPropName = getReposPropName(propName); SVNPropertyValue value = null; Map attributes = property.getAttributes(); if (attributes != null) { for (Iterator attrsIter = attributes.keySet().iterator(); attrsIter.hasNext();) { String attrName = (String) attrsIter.next(); if (ServletDAVHandler.ENCODING_ATTR.equals(attrName)) { String encodingType = (String) attributes.get(attrName); if (ServletDAVHandler.BASE64_ENCODING.equals(encodingType)) { byte[] buffer = new byte[propValue.length()]; int length = SVNBase64.base64ToByteArray(new StringBuffer(propValue), buffer); value = SVNPropertyValue.create(reposPropName, buffer, 0, length); } else { throw new DAVException("Unknown property encoding", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } break; } } } if (value == null) { value = SVNPropertyValue.create(propValue); } saveValue(propName, value); } public void defineNamespaces(Map namespaces) { namespaces.put(DAVElement.SVN_SVN_PROPERTY_NAMESPACE, "S"); namespaces.put(DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE, "C"); namespaces.put(DAVElement.SVN_DAV_PROPERTY_NAMESPACE, "V"); } /** * @return Collection of DAVElement objects */ public Collection getPropertyNames() throws DAVException { FSFS fsfs = myResource.getFSFS(); SVNException exc = null; if (myProperties == null) { if (myResource.isBaseLined()) { if (myResource.getType() == DAVResourceType.WORKING) { try { myProperties = fsfs.getTransactionProperties(myResource.getTxnName()); } catch (SVNException svne) { exc = svne; } } else { try { myProperties = fsfs.getRevisionProperties(myResource.getRevision()); } catch (SVNException svne) { exc = svne; } } } else { FSRoot root = myResource.getRoot(); String path = myResource.getResourceURI().getPath(); try { FSRevisionNode node = root.getRevisionNode(path); myProperties = node.getProperties(fsfs); } catch (SVNException svne) { exc = svne; } if (exc == null) { try { root.checkNodeKind(path); } catch (SVNException svne) { exc = svne; } //TODO: add logging here? } } if (exc != null) { throw DAVException.convertError(exc.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not begin sequencing through properties", null); } } Collection propNames = new ArrayList(); for (Iterator namesIter = myProperties.nameSet().iterator(); namesIter.hasNext();) { String propName = (String) namesIter.next(); DAVElement propElementName = null; if (propName.startsWith(SVNProperty.SVN_PREFIX)) { propElementName = DAVElement.getElement(DAVElement.SVN_SVN_PROPERTY_NAMESPACE, propName.substring(SVNProperty.SVN_PREFIX.length())); } else { propElementName = DAVElement.getElement(DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE, propName); } propNames.add(propElementName); } return propNames; } public boolean outputValue(DAVElement propName, StringBuffer buffer) throws DAVException { SVNPropertyValue propValue = getPropertyValue(propName); boolean found = propValue != null; if (!found) { return found; } String prefix = null; if (DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE.equals(propName.getNamespace())) { prefix = "C"; } else { prefix = "S"; } String propValueString = SVNPropertyValue.getPropertyAsString(propValue); if ("".equals(propValueString)) { SVNXMLUtil.openXMLTag(prefix, propName.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, buffer); } else { String xmlSafeValue = null; Map attrs = null; if (!SVNEncodingUtil.isXMLSafe(propValueString)) { try { xmlSafeValue = SVNBase64.byteArrayToBase64(propValueString.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { xmlSafeValue = SVNBase64.byteArrayToBase64(propValueString.getBytes()); } attrs = new HashMap(); attrs.put("V:encoding", "base64"); } else { xmlSafeValue = SVNEncodingUtil.xmlEncodeCDATA(propValueString); } SVNXMLUtil.openXMLTag(prefix, propName.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, attrs, buffer); buffer.append(xmlSafeValue); SVNXMLUtil.closeXMLTag(prefix, propName.getName(), buffer); } return found; } public SVNPropertyValue getPropertyValue(DAVElement propName) throws DAVException { String reposPropName = getReposPropName(propName); if (reposPropName == null) { return null; } SVNProperties props = null; FSFS fsfs = myResource.getFSFS(); try { //TODO: if myProperties != null, try searching there first if (myResource.isBaseLined()) { if (myResource.getType() == DAVResourceType.WORKING) { FSTransactionInfo txn = myResource.getTxnInfo(); props = fsfs.getTransactionProperties(txn.getTxnId()); } else { long revision = myResource.getRevision(); props = fsfs.getRevisionProperties(revision); } } else { FSRoot root = myResource.getRoot(); props = fsfs.getProperties(root.getRevisionNode(myResource.getResourceURI().getPath())); } } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not fetch a property", null); } if (props != null) { return props.getSVNPropertyValue(reposPropName); } return null; } public DAVResource getResource() { return myResource; } private void saveValue(DAVElement propName, SVNPropertyValue value) throws DAVException { String reposPropName = getReposPropName(propName); if (reposPropName == null) { DAVConfig config = myResource.getRepositoryManager().getDAVConfig(); if (config.isAutoVersioning()) { reposPropName = propName.getName(); } else { throw new DAVException("Properties may only be defined in the {0} and {1} namespaces.", new Object[] { DAVElement.SVN_SVN_PROPERTY_NAMESPACE, DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE }, HttpServletResponse.SC_CONFLICT, 0); } } try { FSFS fsfs = myResource.getFSFS(); if (myResource.isBaseLined()) { if (myResource.isWorking()) { FSTransactionInfo txn = myResource.getTxnInfo(); SVNProperties props = new SVNProperties(); props.put(reposPropName, value); fsfs.changeTransactionProperties(txn.getTxnId(), props); } else { SVNRepository repos = myResource.getRepository(); repos.setRevisionPropertyValue(myResource.getRevision(), reposPropName, value); //TODO: maybe add logging here } } else { DAVResourceURI resourceURI = myResource.getResourceURI(); FSCommitter committer = getCommitter(); committer.changeNodeProperty(resourceURI.getPath(), reposPropName, value); } } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, null); } myProperties = null; } private String getReposPropName(DAVElement propName) { if (DAVElement.SVN_SVN_PROPERTY_NAMESPACE.equals(propName.getNamespace())) { return SVNProperty.SVN_PREFIX + propName.getName(); } else if (DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE.equals(propName.getNamespace())) { return propName.getName(); } return null; } public boolean isOperative() { return myIsOperative; } public boolean isDeferred() { return myIsDeferred; } public void setDeferred(boolean isDeferred) { myIsDeferred = isDeferred; } private void doOpen(boolean readOnly) throws DAVException { myIsOperative = true; DAVResourceType resType = myResource.getType(); if (resType == DAVResourceType.HISTORY || resType == DAVResourceType.ACTIVITY || resType == DAVResourceType.PRIVATE) { myIsOperative = false; return; } if (!readOnly && resType != DAVResourceType.WORKING) { if (!(myResource.isBaseLined() && resType == DAVResourceType.VERSION)) { throw new DAVException("Properties may only be changed on working resources.", HttpServletResponse.SC_CONFLICT, 0); } } } private FSCommitter getCommitter() { return myOwner.getCommitter(myResource.getFSFS(), myResource.getRoot(), myResource.getTxnInfo(), myResource.getLockTokens(), myResource.getUserName()); } } DAVPropfindHandler.java000066400000000000000000001160331177510526000367400ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionRoot; import org.tmatesoft.svn.core.internal.server.dav.DAVConfig; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceKind; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceState; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceURI; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; import org.tmatesoft.svn.core.internal.server.dav.DAVServletUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVPropfindHandler extends ServletDAVHandler implements IDAVResourceWalkHandler { public static final List NAMESPACES = new LinkedList(); static { NAMESPACES.add(DAVElement.DAV_NAMESPACE); NAMESPACES.add(DAVElement.SVN_DAV_PROPERTY_NAMESPACE); } private static final String DEFAULT_AUTOVERSION_LINE = "DAV:checkout-checkin"; private DAVPropfindRequest myDAVRequest; private boolean myIsAllProp; //private boolean myIsPropName; private boolean myIsProp; private DAVElementProperty myDocRoot; private StringBuffer myPropStat404; private StringBuffer myResponseBuffer; private DAVLockInfoProvider myLocksProvider; public DAVPropfindHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); } protected DAVRequest getDAVRequest() { return getPropfindRequest(); } public void execute() throws SVNException { DAVResource resource = getRequestedDAVResource(true, false); DAVResourceState resourceState = getResourceState(resource); if (resourceState == DAVResourceState.NULL) { //TODO: what body should we send? sendError(HttpServletResponse.SC_NOT_FOUND, null); return; } DAVDepth depth = getRequestDepth(DAVDepth.DEPTH_INFINITY); //TODO: check the depth is not less than 0; if it is, send BAD_REQUEST if (depth == DAVDepth.DEPTH_INFINITY && resource.isCollection()) { DAVConfig config = getConfig(); if (!config.isAllowDepthInfinity()) { String message = "PROPFIND requests with a Depth of \"infinity\" are not allowed for " + SVNEncodingUtil.xmlEncodeCDATA(getURI()) + "."; response(message, DAVServlet.getStatusLine(HttpServletResponse.SC_FORBIDDEN), HttpServletResponse.SC_FORBIDDEN); return; } } long readCount = readInput(false); DAVPropfindRequest request = getPropfindRequest(); DAVElementProperty rootElement = request.getRootElement(); if (readCount > 0 && rootElement.getName() != DAVElement.PROPFIND) { //TODO: maybe add logging here later //TODO: what body should we send? sendError(HttpServletResponse.SC_BAD_REQUEST, null); return; } myIsAllProp = false; //myIsPropName = false; myIsProp = false; if (readCount == 0 || rootElement.hasChild(DAVElement.ALLPROP)) { myIsAllProp = true; } else if (rootElement.hasChild(DAVElement.PROPNAME)) { //myIsPropName = true; } else if (rootElement.hasChild(DAVElement.PROP)) { myIsProp = true; } else { //TODO: what body should we send? //TODO: maybe add logging here later setResponseStatus(HttpServletResponse.SC_BAD_REQUEST); return; } myLocksProvider = null; try { myLocksProvider = DAVLockInfoProvider.createLockInfoProvider(this, false); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The lock database could not be opened, preventing access to the various lock properties for the PROPFIND.", null); } myResponseBuffer = new StringBuffer(); DAVXMLUtil.beginMultiStatus(getHttpServletResponse(), SC_MULTISTATUS, getNamespaces(), myResponseBuffer); int walkType = DAVResourceWalker.DAV_WALKTYPE_NORMAL | DAVResourceWalker.DAV_WALKTYPE_AUTH | DAVResourceWalker.DAV_WALKTYPE_LOCKNULL; DAVResourceWalker walker = new DAVResourceWalker(); DAVException error = null; try { walker.walk(myLocksProvider, resource, null, 0, null, walkType, this, depth); } catch (DAVException dave) { error = dave; } if (error != null) { throw new DAVException("Provider encountered an error while streaming", error.getResponseCode(), error, 0); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.MULTISTATUS.getName(), myResponseBuffer); String responseBody = myResponseBuffer.toString(); try { setResponseContentLength(responseBody.getBytes(UTF8_ENCODING).length); } catch (UnsupportedEncodingException e) { setResponseContentLength(responseBody.getBytes().length); } setResponseStatus(SC_MULTISTATUS); try { getResponseWriter().write(responseBody); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } public DAVResponse handleResource(DAVResponse response, DAVResource resource, DAVLockInfoProvider lockInfoProvider, LinkedList ifHeaders, int flags, DAVLockScope lockScope, CallType callType) throws DAVException { DAVPropertiesProvider propsProvider = null; try { propsProvider = DAVPropertiesProvider.createPropertiesProvider(resource, this); } catch (DAVException dave) { if (myIsProp) { cacheBadProps(); DAVPropsResult badProps = new DAVPropsResult(); badProps.addPropStatsText(myPropStat404.toString()); streamResponse(resource, 0, badProps); } else { streamResponse(resource, HttpServletResponse.SC_OK, null); } return null; } DAVPropsResult result = null; if (myIsProp) { result = getProps(propsProvider, getPropfindRequest().getRootElement()); } else { DAVInsertPropAction action = myIsAllProp ? DAVInsertPropAction.INSERT_VALUE : DAVInsertPropAction.INSERT_NAME; result = getAllProps(propsProvider, action); } streamResponse(resource, 0, result); return null; } private DAVPropsResult getAllProps(DAVPropertiesProvider propsProvider, DAVInsertPropAction action) throws DAVException { boolean foundContentType = false; boolean foundContentLang = false; DAVPropsResult result = new DAVPropsResult(); StringBuffer buffer = new StringBuffer(); if (action != DAVInsertPropAction.INSERT_SUPPORTED) { if (propsProvider.isDeferred()) { propsProvider.open(true); } SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); Map namespacesToPrefixes = new HashMap(); propsProvider.defineNamespaces(namespacesToPrefixes); Collection propNames = propsProvider.getPropertyNames(); int ind = 0; for (Iterator propNamesIter = propNames.iterator(); propNamesIter.hasNext();) { DAVElement propNameElement = (DAVElement) propNamesIter.next(); if (DAVElement.DAV_NAMESPACE.equals(propNameElement.getNamespace())) { if (DAVElement.GET_CONTENT_TYPE.getName().equals(propNameElement.getName())) { foundContentType = true; } else if (DAVElement.GET_CONTENT_LANGUAGE.getName().equals(propNameElement.getName())) { foundContentLang = true; } } if (action == DAVInsertPropAction.INSERT_VALUE) { try { propsProvider.outputValue(propNameElement, buffer); } catch (DAVException dave) { //TODO: probably change this behavior in future continue; } } else { ind = outputPropName(propNameElement, namespacesToPrefixes, ind, buffer); } } generateXMLNSNamespaces(result, namespacesToPrefixes); } addAllLivePropNamespaces(result); insertAllLiveProps(propsProvider.getResource(), action, buffer); LivePropertySpecification suppLockSpec = (LivePropertySpecification) OUR_CORE_LIVE_PROPS.get(DAVElement.SUPPORTED_LOCK); insertCoreLiveProperty(propsProvider.getResource(), action, suppLockSpec, buffer); LivePropertySpecification lockDiscoverySpec = (LivePropertySpecification) OUR_CORE_LIVE_PROPS.get(DAVElement.LOCK_DISCOVERY); insertCoreLiveProperty(propsProvider.getResource(), action, lockDiscoverySpec, buffer); if (!foundContentType) { LivePropertySpecification getContentTypeSpec = (LivePropertySpecification) OUR_CORE_LIVE_PROPS.get(DAVElement.GET_CONTENT_TYPE); insertCoreLiveProperty(propsProvider.getResource(), action, getContentTypeSpec, buffer); } if (!foundContentLang) { LivePropertySpecification getContentLanguageSpec = (LivePropertySpecification) OUR_CORE_LIVE_PROPS.get(DAVElement.GET_CONTENT_LANGUAGE); insertCoreLiveProperty(propsProvider.getResource(), action, getContentLanguageSpec, buffer); } if (action != DAVInsertPropAction.INSERT_SUPPORTED) { SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), buffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), "HTTP/1.1 200 OK", null, false, false, buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), buffer); } result.addPropStatsText(buffer.toString()); return result; } private void insertAllLiveProps(DAVResource resource, DAVInsertPropAction propAction, StringBuffer buffer) throws DAVException { if (!resource.exists()) { return; } for (Iterator livePropsIter = OUR_LIVE_PROPS.keySet().iterator(); livePropsIter.hasNext();) { DAVElement propElement = (DAVElement) livePropsIter.next(); if (propElement == DAVElement.COMMENT || propElement == DAVElement.DISPLAY_NAME || propElement == DAVElement.SOURCE) { //only RESOURCETYPE core prop should be inserted continue; } LivePropertySpecification lps = (LivePropertySpecification) OUR_LIVE_PROPS.get(propElement); insertLiveProp(resource, lps, propAction, buffer); } } private DAVPropsResult getProps(DAVPropertiesProvider propsProvider, DAVElementProperty docRootElement) throws DAVException { StringBuffer buffer = new StringBuffer(); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, buffer); StringBuffer badRes = null; Collection xmlnses = new LinkedList(); boolean haveGood = false; boolean definedNamespaces = false; Map namespacesToPrefixes = new HashMap(); int prefixInd = 0; DAVElementProperty propElement = docRootElement.getChild(DAVElement.PROP); List childrenElements = propElement.getChildren(); boolean filledNamespaces = false; for (Iterator childrenIter = childrenElements.iterator(); childrenIter.hasNext();) { DAVElementProperty childElement = (DAVElementProperty) childrenIter.next(); LivePropertySpecification livePropSpec = findLiveProperty(childElement.getName()); if (livePropSpec != null) { DAVInsertPropAction doneAction = insertLiveProp(propsProvider.getResource(), livePropSpec, DAVInsertPropAction.INSERT_VALUE, buffer); if (doneAction == DAVInsertPropAction.INSERT_VALUE) { haveGood = true; if (!filledNamespaces) { int ind = 0; for (Iterator namespacesIter = NAMESPACES.iterator(); namespacesIter.hasNext();) { String namespace = (String) namespacesIter.next(); String xmlns = " xmlns:lp" + ind + "=\"" + namespace + "\""; xmlnses.add(xmlns); ind++; } filledNamespaces = true; } continue; } } if (propsProvider.isDeferred()) { propsProvider.open(true); } boolean found = false; try { found = propsProvider.outputValue(childElement.getName(), buffer); } catch (DAVException dave) { continue; } if (found) { haveGood = true; if (!definedNamespaces) { propsProvider.defineNamespaces(namespacesToPrefixes); definedNamespaces = true; } continue; } if (badRes == null) { badRes = new StringBuffer(); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, badRes); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, badRes); } prefixInd = outputPropName(childElement.getName(), namespacesToPrefixes, prefixInd, buffer); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), buffer); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, buffer); buffer.append("HTTP/1.1 200 OK"); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), buffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), buffer); DAVPropsResult result = new DAVPropsResult(); if (badRes != null) { SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), badRes); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, badRes); badRes.append("HTTP/1.1 404 Not Found"); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), badRes); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), badRes); if (!haveGood) { result.addPropStatsText(badRes.toString()); } else { result.addPropStatsText(buffer.toString()); result.addPropStatsText(badRes.toString()); } } else { result.addPropStatsText(buffer.toString()); } addNamespaces(result, xmlnses); generateXMLNSNamespaces(result, namespacesToPrefixes); return result; } private void addNamespaces(DAVPropsResult result, Collection xmlnses) { for (Iterator xmlnsesIter = xmlnses.iterator(); xmlnsesIter.hasNext();) { String xmlnsString = (String) xmlnsesIter.next(); result.addNamespace(xmlnsString); } } private void addAllLivePropNamespaces(DAVPropsResult result) { for (Iterator namespacesIter = NAMESPACES.iterator(); namespacesIter.hasNext();) { String namespace = (String) namespacesIter.next(); int ind = NAMESPACES.indexOf(namespace); String xmlnsStr = " xmlns:lp" + ind + "=\"" + namespace + "\""; result.addNamespace(xmlnsStr); } } private void generateXMLNSNamespaces(DAVPropsResult result, Map namespacesToPrefixes) { for (Iterator prefixesIter = namespacesToPrefixes.keySet().iterator(); prefixesIter.hasNext();) { String uri = (String) prefixesIter.next(); String prefix = (String) namespacesToPrefixes.get(uri); result.addNamespace(" xmlns:" + prefix + "=\"" + uri + "\""); } } private int outputPropName(DAVElement propName, Map namespacesToPrefixes, int ind, StringBuffer buffer) { if ("".equals(propName.getNamespace())) { SVNXMLUtil.openXMLTag(null, propName.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, buffer); } else { String prefix = namespacesToPrefixes != null ? (String) namespacesToPrefixes.get(propName.getNamespace()) : null; if (prefix == null) { prefix = "g" + ind; namespacesToPrefixes.put(propName.getNamespace(), prefix); } SVNXMLUtil.openXMLTag((String) namespacesToPrefixes.get(propName.getNamespace()), propName.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, buffer); } return ++ind; } private DAVInsertPropAction insertCoreLiveProperty(DAVResource resource, DAVInsertPropAction propAction, LivePropertySpecification livePropSpec, StringBuffer buffer) throws DAVException { DAVInsertPropAction inserted = DAVInsertPropAction.NOT_DEF; DAVElement livePropElement = livePropSpec.getPropertyName(); String value = null; if (livePropElement == DAVElement.LOCK_DISCOVERY) { if (myLocksProvider != null) { DAVLock lock = null; try { lock = myLocksProvider.getLock(resource); } catch (DAVException dave) { throw new DAVException("DAV:lockdiscovery could not be determined due to a problem fetching the locks for this resource.", dave.getResponseCode(), dave, 0); } if (lock == null) { value = ""; } else { value = DAVLockInfoProvider.getActiveLockXML(lock); } } } else if (livePropElement == DAVElement.SUPPORTED_LOCK) { if (myLocksProvider != null) { value = myLocksProvider.getSupportedLock(resource); } } else if (livePropElement == DAVElement.GET_CONTENT_TYPE) { //TODO: get content type from a response when imitating a GET request? } else if (livePropElement == DAVElement.GET_CONTENT_LANGUAGE) { //TODO: get Content-Language from a response when imitating a GET request? } if (value != null) { if (propAction == DAVInsertPropAction.INSERT_SUPPORTED) { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.SUPPORTED_LIVE_PROPERTY.getName(), SVNXMLUtil.XML_STYLE_NORMAL, "D:name", livePropElement.getName(), buffer); } else if (propAction == DAVInsertPropAction.INSERT_VALUE && !"".equals(value)) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, livePropElement.getName(), value, null, false, false, buffer); } else { SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, livePropElement.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, buffer); } inserted = propAction; } return inserted; } private DAVInsertPropAction insertLiveProp(DAVResource resource, LivePropertySpecification livePropSpec, DAVInsertPropAction propAction, StringBuffer buffer) throws DAVException { if (!livePropSpec.isSVNSupported()) { //this is a core WebDAV live prop return insertCoreLiveProperty(resource, propAction, livePropSpec, buffer); } DAVElement livePropElement = livePropSpec.getPropertyName(); if (!resource.exists() && livePropElement != DAVElement.VERSION_CONTROLLED_CONFIGURATION && livePropElement != DAVElement.BASELINE_RELATIVE_PATH) { return DAVInsertPropAction.NOT_SUPP; } String value = null; DAVResourceURI uri = resource.getResourceURI(); if (livePropElement == DAVElement.GET_LAST_MODIFIED || livePropElement == DAVElement.CREATION_DATE) { if (resource.getType() == DAVResourceType.PRIVATE && resource.getKind() == DAVResourceKind.VCC) { return DAVInsertPropAction.NOT_SUPP; } if (livePropElement == DAVElement.CREATION_DATE) { try { value = SVNDate.formatDate(getLastModifiedTime2(resource)); } catch (SVNException svne) { return DAVInsertPropAction.NOT_DEF; } } else if (livePropElement == DAVElement.GET_LAST_MODIFIED) { try { value = SVNDate.formatRFC1123Date(getLastModifiedTime2(resource)); } catch (SVNException svne) { return DAVInsertPropAction.NOT_DEF; } } value = SVNEncodingUtil.xmlEncodeCDATA(value, true); } else if (livePropElement == DAVElement.CREATOR_DISPLAY_NAME) { if (resource.getType() == DAVResourceType.PRIVATE && resource.getKind() == DAVResourceKind.VCC) { return DAVInsertPropAction.NOT_SUPP; } long committedRev = -1; if (resource.isBaseLined() && resource.getType() == DAVResourceType.VERSION) { committedRev = resource.getRevision(); } else if (resource.getType() == DAVResourceType.REGULAR || resource.getType() == DAVResourceType.WORKING || resource.getType() == DAVResourceType.VERSION) { try { committedRev = resource.getCreatedRevisionUsingFS(null); } catch (SVNException svne) { value = "###error###"; } } else { return DAVInsertPropAction.NOT_SUPP; } String lastAuthor = null; try { lastAuthor = resource.getAuthor(committedRev); } catch (SVNException svne) { value = "###error###"; } if (lastAuthor == null) { return DAVInsertPropAction.NOT_DEF; } value = SVNEncodingUtil.xmlEncodeCDATA(lastAuthor, true); } else if (livePropElement == DAVElement.GET_CONTENT_LANGUAGE) { return DAVInsertPropAction.NOT_SUPP; } else if (livePropElement == DAVElement.GET_CONTENT_LENGTH) { if (resource.isCollection() || resource.isBaseLined()) { return DAVInsertPropAction.NOT_SUPP; } long fileSize = 0; try { fileSize = resource.getContentLength(null); value = String.valueOf(fileSize); } catch (SVNException e) { value = "0"; } } else if (livePropElement == DAVElement.GET_CONTENT_TYPE) { if (resource.isBaseLined() && resource.getType() == DAVResourceType.VERSION) { return DAVInsertPropAction.NOT_SUPP; } if (resource.getType() == DAVResourceType.PRIVATE && resource.getKind() == DAVResourceKind.VCC) { return DAVInsertPropAction.NOT_SUPP; } if (resource.isCollection()) { value = DAVResource.DEFAULT_COLLECTION_CONTENT_TYPE; } else { SVNPropertyValue contentType = null; try { contentType = resource.getProperty(null, SVNProperty.MIME_TYPE); } catch (SVNException svne) { // } if (contentType != null) { value = contentType.getString(); } else if (!resource.isSVNClient() && getRequest().getContentType() != null) { value = getRequest().getContentType(); } else { value = DAVResource.DEFAULT_FILE_CONTENT_TYPE; } try { SVNPropertiesManager.validateMimeType(value); } catch (SVNException svne) { return DAVInsertPropAction.NOT_DEF; } } } else if (livePropElement == DAVElement.GET_ETAG) { if (resource.getType() == DAVResourceType.PRIVATE && resource.getKind() == DAVResourceKind.VCC) { return DAVInsertPropAction.NOT_SUPP; } value = resource.getETag(); } else if (livePropElement == DAVElement.AUTO_VERSION) { if (getConfig().isAutoVersioning()) { value = DEFAULT_AUTOVERSION_LINE; } else { return DAVInsertPropAction.NOT_DEF; } } else if (livePropElement == DAVElement.BASELINE_COLLECTION) { if (resource.getType() != DAVResourceType.VERSION || !resource.isBaseLined()) { return DAVInsertPropAction.NOT_SUPP; } value = DAVPathUtil.buildURI(uri.getContext(), DAVResourceKind.BASELINE_COLL, resource.getRevision(), null, true); } else if (livePropElement == DAVElement.CHECKED_IN) { String s = null; if (resource.getType() == DAVResourceType.PRIVATE && resource.getKind() == DAVResourceKind.VCC) { long revNum = -1; try { revNum = resource.getLatestRevision(); s = DAVPathUtil.buildURI(uri.getContext(), DAVResourceKind.BASELINE, revNum, null, false); StringBuffer buf = SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), s, null, true, true, null); value = buf.toString(); } catch (SVNException svne) { value = "###error###"; } } else if (resource.getType() != DAVResourceType.REGULAR) { return DAVInsertPropAction.NOT_SUPP; } else { long revToUse = DAVServletUtil.getSafeCreatedRevision((FSRevisionRoot) resource.getRoot(), uri.getPath()); s = DAVPathUtil.buildURI(uri.getContext(), DAVResourceKind.VERSION, revToUse, uri.getPath(), false); StringBuffer buf = SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.HREF.getName(), s, null, true, true, null); value = buf.toString(); } } else if (livePropElement == DAVElement.VERSION_CONTROLLED_CONFIGURATION) { if (resource.getType() != DAVResourceType.REGULAR) { return DAVInsertPropAction.NOT_SUPP; } value = DAVPathUtil.buildURI(uri.getContext(), DAVResourceKind.VCC, -1, null, true); } else if (livePropElement == DAVElement.VERSION_NAME) { if (resource.getType() != DAVResourceType.VERSION && !resource.isVersioned()) { return DAVInsertPropAction.NOT_SUPP; } if (resource.getType() == DAVResourceType.PRIVATE && resource.getKind() == DAVResourceKind.VCC) { return DAVInsertPropAction.NOT_SUPP; } if (resource.isBaseLined()) { value = String.valueOf(resource.getRevision()); } else { try { long committedRev = resource.getCreatedRevisionUsingFS(null); value = String.valueOf(committedRev); value = SVNEncodingUtil.xmlEncodeCDATA(value, true); } catch (SVNException svne) { value = "###error###"; } } } else if (livePropElement == DAVElement.BASELINE_RELATIVE_PATH) { if (resource.getType() != DAVResourceType.REGULAR) { return DAVInsertPropAction.NOT_SUPP; } value = SVNEncodingUtil.xmlEncodeCDATA(DAVPathUtil.dropLeadingSlash(uri.getPath()), true); } else if (livePropElement == DAVElement.MD5_CHECKSUM) { if (!resource.isCollection() && !resource.isBaseLined() && (resource.getType() == DAVResourceType.REGULAR || resource.getType() == DAVResourceType.VERSION || resource.getType() == DAVResourceType.WORKING)) { try { value = resource.getMD5Checksum(null); if (value == null) { return DAVInsertPropAction.NOT_SUPP; } } catch (SVNException svne) { value = "###error###"; } } else { return DAVInsertPropAction.NOT_SUPP; } } else if (livePropElement == DAVElement.REPOSITORY_UUID) { try { value = resource.getRepositoryUUID(false); } catch (SVNException svne) { value = "###error###"; } } else if (livePropElement == DAVElement.DEADPROP_COUNT) { if (resource.getType() != DAVResourceType.REGULAR) { return DAVInsertPropAction.NOT_SUPP; } SVNProperties props = null; try { props = resource.getSVNProperties(null); int deadPropertiesCount = props.size(); value = String.valueOf(deadPropertiesCount); } catch (SVNException svne) { value = "###error###"; } } else if (livePropElement == DAVElement.RESOURCE_TYPE) { if (resource.getType() == DAVResourceType.VERSION) { if (resource.isBaseLined()) { StringBuffer buf = SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.BASELINE.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, null); value = buf.toString(); } } else if (resource.getType() == DAVResourceType.REGULAR || resource.getType() == DAVResourceType.WORKING) { if (resource.isCollection()) { StringBuffer buf = SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.COLLECTION.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, null); value = buf.toString(); } else { value = ""; } } else if (resource.getType() == DAVResourceType.HISTORY) { StringBuffer buf = SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.VERSION_HISTORY.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, null); value = buf.toString(); } else if (resource.getType() == DAVResourceType.WORKSPACE) { StringBuffer buf = SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.COLLECTION.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, null); value = buf.toString(); } else if (resource.getType() == DAVResourceType.ACTIVITY) { StringBuffer buf = SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.ACTIVITY.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING | SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, null); value = buf.toString(); } else { return DAVInsertPropAction.NOT_DEF; } } else if (livePropElement == DAVElement.COMMENT || livePropElement == DAVElement.CREATOR_DISPLAY_NAME || livePropElement == DAVElement.DISPLAY_NAME || livePropElement == DAVElement.SOURCE) { return DAVInsertPropAction.NOT_DEF; } else { return DAVInsertPropAction.NOT_SUPP; } int ind = NAMESPACES.indexOf(livePropElement.getNamespace()); String prefix = "lp" + ind; if (propAction == DAVInsertPropAction.INSERT_NAME || (propAction == DAVInsertPropAction.INSERT_VALUE && (value == null || value.length() == 0))) { SVNXMLUtil.openXMLTag(prefix, livePropElement.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, buffer); } else if (propAction == DAVInsertPropAction.INSERT_VALUE) { SVNXMLUtil.openCDataTag(prefix, livePropElement.getName(), value, null, false, false, buffer); } else { Map attrs = new HashMap(); attrs.put("D:name", livePropElement.getName()); attrs.put("D:namespace", livePropElement.getNamespace()); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.SUPPORTED_LIVE_PROPERTY.getName(), SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, buffer); } return propAction; } private Date getLastModifiedTime2(DAVResource resource) throws SVNException { long revision = -1; if (resource.isBaseLined() && resource.getType() == DAVResourceType.VERSION) { revision = resource.getRevision(); } else if (resource.getType() == DAVResourceType.REGULAR || resource.getType() == DAVResourceType.WORKING || resource.getType() == DAVResourceType.VERSION) { revision = resource.getCreatedRevisionUsingFS(null); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_PROPS_NOT_FOUND, "Failed to determine property"), SVNLogType.NETWORK); } return resource.getRevisionDate(revision); } private void streamResponse(DAVResource resource, int status, DAVPropsResult propStats) { DAVResponse response = new DAVResponse(null, resource.getResourceURI().getRequestURI(), null, propStats, status); DAVXMLUtil.sendOneResponse(response, myResponseBuffer); } private void cacheBadProps() { if (myPropStat404 != null) { return; } myPropStat404 = new StringBuffer(); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, myPropStat404); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), SVNXMLUtil.XML_STYLE_PROTECT_CDATA, null, myPropStat404); DAVElementProperty elem = myDocRoot.getChild(DAVElement.PROP); List childrenElements = elem.getChildren(); for (Iterator childrenIter = childrenElements.iterator(); childrenIter.hasNext();) { DAVElementProperty childElement = (DAVElementProperty) childrenIter.next(); DAVXMLUtil.addEmptyElement(DAVPropfindHandler.this.getNamespaces(), childElement.getName(), myPropStat404); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROP.getName(), myPropStat404); SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), SVNXMLUtil.XML_STYLE_NORMAL, null, myPropStat404); myPropStat404.append("HTTP/1.1 404 Not Found"); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.STATUS.getName(), myPropStat404); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.PROPSTAT.getName(), myPropStat404); } private DAVPropfindRequest getPropfindRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVPropfindRequest(); } return myDAVRequest; } private static class DAVInsertPropAction { public static final DAVInsertPropAction NOT_DEF = new DAVInsertPropAction(); public static final DAVInsertPropAction NOT_SUPP = new DAVInsertPropAction(); public static final DAVInsertPropAction INSERT_VALUE = new DAVInsertPropAction(); public static final DAVInsertPropAction INSERT_NAME = new DAVInsertPropAction(); public static final DAVInsertPropAction INSERT_SUPPORTED = new DAVInsertPropAction(); private DAVInsertPropAction() { } } } DAVPropfindRequest.java000066400000000000000000000046721177510526000370200ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVPropfindRequest extends DAVRequest { private static final DAVElement PROPFIND = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "propfind"); private static final DAVElement PROPNAME = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "propname"); private static final DAVElement ALLPROP = DAVElement.getElement(DAVElement.DAV_NAMESPACE, "allprop"); public DAVPropfindRequest() { super(); } protected void init() throws SVNException { if (getRoot().getName() != PROPFIND) { invalidXML(); } } public boolean isAllPropRequest() throws SVNException { return getRoot().hasChild(ALLPROP); } public boolean isPropNameRequest() throws SVNException { return getRoot().hasChild(PROPNAME); } public boolean isPropRequest() throws SVNException { return getRoot().hasChild(DAVElement.PROP); } public Collection getPropertyElements() throws SVNException { DAVElementProperty propElement = getRoot().getChild(DAVElement.PROP); List props = new LinkedList(); List children = propElement.getChildren(); if (children != null) { for (Iterator childrenIter = children.iterator(); childrenIter.hasNext();) { DAVElementProperty child = (DAVElementProperty) childrenIter.next(); props.add(child.getName()); } } return props; } private DAVElementProperty getRoot() throws SVNException { if (getRootElement() == null) { invalidXML(); } return getRootElement(); } } DAVPropsResult.java000066400000000000000000000026341177510526000361640ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Collection; import java.util.LinkedList; /** * @version 1.1.2 * @author TMate Software Ltd. */ public class DAVPropsResult { private StringBuffer myPropStats; private Collection myNamespaces; public void addNamespace(String namespace) { if (myNamespaces == null) { myNamespaces = new LinkedList(); } myNamespaces.add(namespace); } public void addPropStatsText(String text) { if (myPropStats == null) { myPropStats = new StringBuffer(); } myPropStats.append(text); } public Collection getNamespaces() { return myNamespaces; } public String getPropStatsText() { if (myPropStats != null) { return myPropStats.toString(); } return null; } } DAVPutHandler.java000066400000000000000000000171001177510526000357220ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.delta.SVNDeltaReader; import org.tmatesoft.svn.core.internal.io.fs.FSCommitter; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceState; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.io.ISVNDeltaConsumer; import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVPutHandler extends ServletDAVHandler { public DAVPutHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } public void execute() throws SVNException { DAVResource resource = getRequestedDAVResource(false, false); if (resource.getType() != DAVResourceType.REGULAR && resource.getType() != DAVResourceType.WORKING) { String body = "Cannot create resource " + SVNEncodingUtil.xmlEncodeCDATA(getURI()) + " with PUT."; response(body, DAVServlet.getStatusLine(HttpServletResponse.SC_CONFLICT), HttpServletResponse.SC_CONFLICT); return; } if (resource.isCollection()) { response("Cannot PUT to a collection.", DAVServlet.getStatusLine(HttpServletResponse.SC_CONFLICT), HttpServletResponse.SC_CONFLICT); return; } DAVResourceState resourceState = getResourceState(resource); validateRequest(resource, DAVDepth.DEPTH_ZERO, resourceState == DAVResourceState.NULL ? DAV_VALIDATE_PARENT : DAV_VALIDATE_RESOURCE, null, null, null); DAVAutoVersionInfo avInfo = autoCheckOut(resource, false); int mode = DAV_MODE_WRITE_TRUNC; long[] range = parseRange(); if (range != null) { mode = DAV_MODE_WRITE_SEEKABLE; } SVNDeltaReader deltaReader = null; DAVException error = null; try { deltaReader = openStream(resource, mode); } catch (DAVException dave) { error = new DAVException("Unable to PUT new contents for {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(getURI()) }, HttpServletResponse.SC_FORBIDDEN, dave, 0); } if (error == null && range != null) { error = new DAVException("Resource body read/write cannot use ranges (at this time)", HttpServletResponse.SC_NOT_IMPLEMENTED, 0); } DAVException error2 = null; if (error == null) { String path = resource.getResourceURI().getPath(); FSRoot root = resource.getRoot(); FSFS fsfs = resource.getFSFS(); FSTransactionInfo txn = resource.getTxnInfo(); Collection lockTokens = resource.getLockTokens(); String userName = resource.getUserName(); FSCommitter committer = getCommitter(fsfs, root, txn, lockTokens, userName); ISVNDeltaConsumer deltaConsumer = getDeltaConsumer(root, committer, fsfs, userName, lockTokens); SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator(); InputStream inputStream = null; try { inputStream = getRequestInputStream(); byte[] buffer = new byte[2048]; int readCount = -1; while ((readCount = inputStream.read(buffer)) != -1) { if (readCount == 0) { continue; } if (deltaReader != null) { deltaReader.nextWindow(buffer, 0, readCount, path, deltaConsumer); } else { deltaGenerator.sendDelta(path, buffer, readCount, deltaConsumer); } } } catch (IOException ioe) { error = new DAVException("An error occurred while reading the request body.", HttpServletResponse.SC_BAD_REQUEST, 0); } catch (SVNException svne) { error = DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not write the file contents", null); } finally { SVNFileUtil.closeFile(inputStream); if (deltaReader != null) { try { deltaReader.reset(path, deltaConsumer); } catch (SVNException svne) { error2 = DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error finalizing applying windows", null); } if (error2 != null && error == null) { error = error2; } deltaConsumer.textDeltaEnd(path); } } } if (error == null) { resource.setExists(true); } try { autoCheckIn(resource, error != null, false, avInfo); } catch (DAVException dave) { error2 = dave; } if (error != null) { throw error; } if (error2 != null) { error2 = new DAVException("The PUT was successful, but there was a problem automatically checking in the resource or its parent collection.", null, error2.getResponseCode(), error2, 0); //TODO: add here better logging } DAVLockInfoProvider lockProvider = null; try { lockProvider = DAVLockInfoProvider.createLockInfoProvider(this, false); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The file was PUT successfully, but there was a problem opening the lock database which prevents inheriting locks from the parent resources.", null); } notifyCreated(resource, lockProvider, resourceState, DAVDepth.DEPTH_ZERO); handleDAVCreated(null, "Resource", resourceState == DAVResourceState.EXISTS); } protected DAVRequest getDAVRequest() { return null; } } DAVReplayHandler.java000066400000000000000000000211471177510526000364140ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.OutputStream; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.util.SVNBase64; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.io.diff.SVNDiffWindow; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVReplayHandler extends DAVReportHandler implements ISVNEditor { private DAVReplayRequest myDAVRequest; private DAVReportHandler myCommonReportHandler; public DAVReplayHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(repositoryManager, request, response); myCommonReportHandler = commonReportHandler; } protected DAVRequest getDAVRequest() { return getReplayRequest(); } private DAVReplayRequest getReplayRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVReplayRequest(); } return myDAVRequest; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace("The request does not contain the 'svn:' namespace, so it is not going" + " to have an svn:revision element. That element is required."); setDAVResource(getRequestedDAVResource(false, false)); writeXMLHeader(null); getRequestedRepository().replay(getReplayRequest().getLowRevision(), getReplayRequest().getRevision(), getReplayRequest().isSendDeltas(), this); writeXMLFooter(null); } private SVNRepository getRequestedRepository() throws SVNException { if (getDAVResource().getResourceURI().getPath() == null || getDAVResource().getResourceURI().getPath().length() == 0) { return getDAVResource().getRepository(); } SVNURL resourceURL = getDAVResource().getRepository().getLocation(); SVNURL resultURL = resourceURL.appendPath(getDAVResource().getResourceURI().getPath(), true); return SVNRepositoryFactory.create(resultURL); } public void targetRevision(long revision) throws SVNException { StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "target-revision", SVNXMLUtil.XML_STYLE_SELF_CLOSING, "rev", String.valueOf(revision), null); write(xmlBuffer); } public void openRoot(long revision) throws SVNException { StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "open-root", SVNXMLUtil.XML_STYLE_SELF_CLOSING, REVISION_ATTR, String.valueOf(revision), null); write(xmlBuffer); } public void deleteEntry(String path, long revision) throws SVNException { Map attrs = new SVNHashMap(); attrs.put(NAME_ATTR, path); attrs.put(REVISION_ATTR, String.valueOf(revision)); StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "delete-entry", SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, null); write(xmlBuffer); } public void absentDir(String path) throws SVNException { } public void absentFile(String path) throws SVNException { } public void addDir(String path, String copyFromPath, long copyFromRevision) throws SVNException { addEntry("add-directory", path, copyFromPath, copyFromRevision); } public void openDir(String path, long revision) throws SVNException { openEntry("open-directory", path, revision); } public void changeDirProperty(String name, SVNPropertyValue value) throws SVNException { changeEntryProperty("change-directory-prop", name, value); } public void closeDir() throws SVNException { StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "close-directory", SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, null); write(xmlBuffer); } public void addFile(String path, String copyFromPath, long copyFromRevision) throws SVNException { addEntry("add-file", path, copyFromPath, copyFromRevision); } public void openFile(String path, long revision) throws SVNException { openEntry("open-file", path, revision); } public void changeFileProperty(String path, String name, SVNPropertyValue value) throws SVNException { changeEntryProperty("change-file-prop", name, value); } public void closeFile(String path, String textChecksum) throws SVNException { Map attrs = new SVNHashMap(); if (textChecksum != null) { attrs.put(CHECKSUM_ATTR, textChecksum); } StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "close-file", SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, null); write(xmlBuffer); } public SVNCommitInfo closeEdit() throws SVNException { return null; } public void applyTextDelta(String path, String baseChecksum) throws SVNException { Map attrs = new SVNHashMap(); if (baseChecksum != null) { attrs.put(CHECKSUM_ATTR, baseChecksum); } StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "apply-textdelta", SVNXMLUtil.XML_STYLE_PROTECT_CDATA, attrs, null); write(xmlBuffer); } public OutputStream textDeltaChunk(String path, SVNDiffWindow diffWindow) throws SVNException { writeTextDeltaChunk(diffWindow); return null; } public void textDeltaEnd(String path) throws SVNException { textDeltaChunkEnd(); setWriteTextDeltaHeader(true); StringBuffer xmlBuffer = SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "apply-textdelta", null); write(xmlBuffer); } public void abortEdit() throws SVNException { } private void addEntry(String tagName, String path, String copyfromPath, long copyfromRevision) throws SVNException { Map attrs = new SVNHashMap(); attrs.put(NAME_ATTR, path); if (copyfromPath != null) { attrs.put(COPYFROM_PATH_ATTR, copyfromPath); attrs.put(COPYFROM_REVISION_ATTR, String.valueOf(copyfromRevision)); } StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, null); write(xmlBuffer); } private void openEntry(String tagName, String path, long revision) throws SVNException { Map attrs = new SVNHashMap(); attrs.put(NAME_ATTR, path); attrs.put(REVISION_ATTR, String.valueOf(revision)); StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_SELF_CLOSING, attrs, null); write(xmlBuffer); } private void changeEntryProperty(String tagName, String name, SVNPropertyValue propertyValue) throws SVNException { StringBuffer xmlBuffer = new StringBuffer(); if (propertyValue != null) { String value = SVNBase64.byteArrayToBase64(SVNPropertyValue.getPropertyAsBytes(propertyValue)); SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_PROTECT_CDATA, NAME_ATTR, name, xmlBuffer); xmlBuffer.append(value); SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, xmlBuffer); } else { Map attrs = new SVNHashMap(); attrs.put(NAME_ATTR, name); attrs.put(DELETE_ATTR, Boolean.TRUE.toString()); SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, "", attrs, xmlBuffer); } write(xmlBuffer); } } DAVReplayRequest.java000066400000000000000000000100241177510526000364570ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import java.util.List; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVReplayRequest extends DAVRequest { private static final DAVElement EDITOR_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "editor-report"); private static final DAVElement LOW_WATER_MARK = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "low-water-mark"); private static final DAVElement SEND_DELTAS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "send-deltas"); boolean myIsSendDeltas = true; long myLowRevision = DAVResource.INVALID_REVISION; long myRevision = DAVResource.INVALID_REVISION; public boolean isSendDeltas() { return myIsSendDeltas; } private void setSendDeltas(boolean isSendDelta) { myIsSendDeltas = isSendDelta; } public long getLowRevision() { return myLowRevision; } private void setLowRevision(long lowRevision) { myLowRevision = lowRevision; } public long getRevision() { return myRevision; } private void setRevision(long revision) { myRevision = revision; } protected void init() throws SVNException { DAVElementProperty rootElement = getRootElement(); rootElement.setElementName(EDITOR_REPORT); List children = rootElement.getChildren(); for (Iterator iterator = children.iterator(); iterator.hasNext();) { DAVElementProperty property = (DAVElementProperty) iterator.next(); DAVElement element = property.getName(); if (element == DAVElement.REVISION) { assertNullCData(element, property); try { setRevision(Long.parseLong(property.getFirstValue(true))); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (element == LOW_WATER_MARK) { assertNullCData(element, property); try { setLowRevision(Long.parseLong(property.getFirstValue(true))); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (element == SEND_DELTAS) { assertNullCData(element, property); int sendDeltas = Integer.parseInt(property.getFirstValue(true)); setSendDeltas(sendDeltas != 0); } } if (!SVNRevision.isValidRevisionNumber(getRevision())) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Request was missing the revision argument."), SVNLogType.NETWORK); } if (!SVNRevision.isValidRevisionNumber(getLowRevision())) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Request was missing the low-water-mark argument."), SVNLogType.NETWORK); } } } DAVReportHandler.java000066400000000000000000000336621177510526000364400ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNBase64; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNHashSet; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.diff.SVNDiffWindow; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.Attributes; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVReportHandler extends ServletDAVHandler { protected static final Set REPORT_NAMESPACES = new SVNHashSet(); protected static final String PATH_ATTR = "path"; protected static final String REVISION_ATTR = "rev"; protected static final String COPYFROM_PATH_ATTR = "copyfrom-path"; protected static final String COPYFROM_REVISION_ATTR = "copyfrom-rev"; protected static final String TXDELTA_ATTR = "txdelta"; protected static final String CHECKSUM_ATTR = "checksum"; protected static final String DELETE_ATTR = "del"; protected static final String LOCK_TOKEN_ATTR = "lock-token"; protected static final String LINKPATH_ATTR = "linkpath"; protected static final String DEPTH_ATTR = "depth"; protected static final String START_EMPTY_ATTR = "start-empty"; protected static final String SEND_ALL_ATTR = "send-all"; protected static final String BASE_CHECKSUM_ATTR = "base-checksum"; protected static final String BC_URL_ATTR = "bc-url"; private DAVRepositoryManager myRepositoryManager; private HttpServletRequest myRequest; private HttpServletResponse myResponse; private DAVReportHandler myReportHandler; private DAVResource myDAVResource; private OutputStream myDiffWindowWriter; private boolean myWriteTextDeltaHeader = true; private boolean mySVNDiffVersion = false; private boolean myIsUnknownReport; static { REPORT_NAMESPACES.add(DAVElement.SVN_NAMESPACE); } protected DAVReportHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); myRepositoryManager = connector; myRequest = request; myResponse = response; } protected List getNamespaces() { return super.getNamespaces(); } protected DAVRequest getDAVRequest() { return getReportHandler().getDAVRequest(); } private DAVReportHandler getReportHandler() { return myReportHandler; } private void setReportHandler(DAVReportHandler reportHandler) { myReportHandler = reportHandler; } protected DAVResource getDAVResource() { return myDAVResource; } protected void setDAVResource(DAVResource DAVResource) { myDAVResource = DAVResource; } protected void checkSVNNamespace(String errorMessage) throws DAVException { errorMessage = errorMessage == null ? "The request does not contain the 'svn:' namespace, so it is not going to have certain required elements." : errorMessage; List namespaces = getNamespaces(); if (!namespaces.contains(DAVElement.SVN_NAMESPACE)) { throw new DAVException(errorMessage, HttpServletResponse.SC_BAD_REQUEST, SVNLogType.NETWORK, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE); } } public boolean doCompress() { return mySVNDiffVersion; } public void setSVNDiffVersion(boolean SVNDiffVersion) { mySVNDiffVersion = SVNDiffVersion; } private boolean isWriteTextDeltaHeader() { return myWriteTextDeltaHeader; } protected void setWriteTextDeltaHeader(boolean writeTextDeltaHeader) { myWriteTextDeltaHeader = writeTextDeltaHeader; } protected void startElement(DAVElement parent, DAVElement element, Attributes attrs) throws SVNException { if (parent == null) { initReportHandler(element); } getReportHandler().handleAttributes(parent, element, attrs); } protected void handleAttributes(DAVElement parent, DAVElement element, Attributes attrs) throws SVNException { getDAVRequest().startElement(parent, element, attrs); } protected void endElement(DAVElement parent, DAVElement element, StringBuffer cdata) throws SVNException { getReportHandler().handleCData(parent, element, cdata); } protected void handleCData(DAVElement parent, DAVElement element, StringBuffer cdata) throws SVNException { getDAVRequest().endElement(parent, element, cdata); } public void execute() throws SVNException { long read = readInput(false); if (myIsUnknownReport) { throw new DAVException("The requested report is unknown.", null, HttpServletResponse.SC_NOT_IMPLEMENTED, null, SVNLogType.DEFAULT, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } if (read == 0) { throw new DAVException("The request body must specify a report.", HttpServletResponse.SC_BAD_REQUEST, SVNLogType.NETWORK); } setDefaultResponseHeaders(); setResponseContentType(DEFAULT_XML_CONTENT_TYPE); setResponseStatus(HttpServletResponse.SC_OK); getReportHandler().execute(); } private void initReportHandler(DAVElement rootElement) { myIsUnknownReport = false; if (rootElement == DATED_REVISIONS_REPORT) { setReportHandler(new DAVDatedRevisionHandler(myRepositoryManager, myRequest, myResponse)); } else if (rootElement == FILE_REVISIONS_REPORT) { setReportHandler(new DAVFileRevisionsHandler(myRepositoryManager, myRequest, myResponse, this)); } else if (rootElement == GET_LOCATIONS) { setReportHandler(new DAVGetLocationsHandler(myRepositoryManager, myRequest, myResponse, this)); } else if (rootElement == LOG_REPORT) { setReportHandler(new DAVLogHandler(myRepositoryManager, myRequest, myResponse, this)); } else if (rootElement == MERGEINFO_REPORT) { setReportHandler(new DAVMergeInfoHandler(myRepositoryManager, myRequest, myResponse, this)); } else if (rootElement == GET_LOCKS_REPORT) { setReportHandler(new DAVGetLocksHandler(myRepositoryManager, myRequest, myResponse)); } else if (rootElement == REPLAY_REPORT) { setReportHandler(new DAVReplayHandler(myRepositoryManager, myRequest, myResponse, this)); } else if (rootElement == UPDATE_REPORT) { setReportHandler(new DAVUpdateHandler(myRepositoryManager, myRequest, myResponse, this)); } else if (rootElement == GET_LOCATION_SEGMENTS) { setReportHandler(new DAVGetLocationSegmentsHandler(myRepositoryManager, myRequest, myResponse, this)); } else if (rootElement == GET_DELETED_REVISION_REPORT) { setReportHandler(new DAVGetDeletedRevisionHandler(myRepositoryManager, myRequest, myResponse, this)); } else { myIsUnknownReport = true; setReportHandler(new DumpReportHandler(myRepositoryManager, myRequest, myResponse)); } } protected void write(String string) throws SVNException { try { getResponseWriter().write(string); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } protected void write(StringBuffer stringBuffer) throws SVNException { write(stringBuffer.toString()); } protected void writeXMLHeader(String tagName) throws SVNException { StringBuffer xmlBuffer = new StringBuffer(); addXMLHeader(xmlBuffer, tagName); write(xmlBuffer); } protected void writeXMLFooter(String tagName) throws SVNException { StringBuffer xmlBuffer = new StringBuffer(); addXMLFooter(xmlBuffer, tagName); write(xmlBuffer); } protected void addXMLHeader(StringBuffer xmlBuffer, String tagName) { SVNXMLUtil.addXMLHeader(xmlBuffer); DAVElementProperty rootElement = getDAVRequest().getRootElement(); tagName = tagName == null ? rootElement.getName().getName() : tagName; DAVXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, REPORT_NAMESPACES, xmlBuffer, false); } protected void addXMLFooter(StringBuffer xmlBuffer, String tagName) { DAVElementProperty rootElement = getDAVRequest().getRootElement(); tagName = tagName == null ? rootElement.getName().getName() : tagName; SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, xmlBuffer); } protected void writeTextDeltaChunk(SVNDiffWindow diffWindow) throws SVNException { if (myDiffWindowWriter == null) { myDiffWindowWriter = new DAVBase64OutputStream(getResponseWriter()); } try { diffWindow.writeTo(myDiffWindowWriter, isWriteTextDeltaHeader(), doCompress()); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } finally { setWriteTextDeltaHeader(false); } } protected void textDeltaChunkEnd() throws SVNException { if (myDiffWindowWriter != null) { try { myDiffWindowWriter.flush(); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } myDiffWindowWriter = null; } protected void writePropertyTag(String tagName, String propertyName, SVNPropertyValue propertyValue) throws SVNException { StringBuffer xmlBuffer; if (propertyValue == null){ xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_SELF_CLOSING, NAME_ATTR, propertyName, null); write(xmlBuffer); return; } String value = propertyValue.getString(); boolean isXMLSafe = true; if (propertyValue.isBinary()){ CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); try { value = decoder.decode(ByteBuffer.wrap(propertyValue.getBytes())).toString(); } catch (CharacterCodingException e) { isXMLSafe = false; } } if (value != null){ isXMLSafe = SVNEncodingUtil.isXMLSafe(value); } if (!isXMLSafe){ byte[] buffer = null; if (value != null){ try { buffer = value.getBytes(UTF8_ENCODING); } catch (UnsupportedEncodingException e) { buffer = value.getBytes(); } } else { buffer = propertyValue.getBytes(); } value = SVNBase64.byteArrayToBase64(buffer); Map attrs = new SVNHashMap(); attrs.put(NAME_ATTR, propertyName); attrs.put(ServletDAVHandler.ENCODING_ATTR, BASE64_ENCODING); xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_PROTECT_CDATA, attrs, null); write(xmlBuffer); write(value); xmlBuffer = SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, null); write(xmlBuffer); } else { xmlBuffer = SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, propertyValue.getString(), NAME_ATTR, propertyName, null); write(xmlBuffer); } } private static class DumpReportHandler extends DAVReportHandler { private DAVRequest myDAVRequest; protected DumpReportHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { super(connector, request, response); } protected DAVRequest getDAVRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVRequest() { protected void init() throws SVNException { } }; } return myDAVRequest; } } } DAVRequest.java000066400000000000000000000061621177510526000353120ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.Attributes; /** * @author TMate Software Ltd. * @version 1.2.0 */ public abstract class DAVRequest { protected static final String NAME_ATTR = "name"; protected static final String NAMESPACE_ATTR = "namespace"; private DAVElementProperty myRootElementProperty; private DAVElementProperty myCurrentElement; public DAVElementProperty getRootElement() { return myRootElementProperty; } protected String getRootElementAttributeValue(String name) { if (myRootElementProperty != null) { return myRootElementProperty.getAttributeValue(name); } return null; } public void startElement(DAVElement parent, DAVElement element, Attributes attrs) throws SVNException { if (parent == null) { myCurrentElement = new DAVElementProperty(element, null); myCurrentElement.setAttributes(attrs); myRootElementProperty = myCurrentElement; } else { myCurrentElement = myCurrentElement.addChild(element, attrs); } } public void endElement(DAVElement parent, DAVElement element, StringBuffer cdata) throws SVNException { if (myCurrentElement == null || element != myCurrentElement.getName()) { invalidXML(); } if (cdata != null) { myCurrentElement.addValue(cdata.toString()); } myCurrentElement = myCurrentElement.getParent(); if (myCurrentElement == null && parent != null) { invalidXML(); } } protected abstract void init() throws SVNException; protected void invalidXML() throws SVNException { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.XML_MALFORMED, "Malformed XML"), SVNLogType.NETWORK); } protected void invalidXML(DAVElement element) throws SVNException { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.XML_MALFORMED, "\"The request's ''{0}'' element is malformed; there is a problem with the client.", element.getName()), SVNLogType.NETWORK); } protected void assertNullCData(DAVElement element, DAVElementProperty property) throws SVNException { if (property.getValues() == null) { invalidXML(element); } } } DAVResourceWalker.java000066400000000000000000000125111177510526000366120ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.internal.io.fs.FSEntry; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionNode; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.handlers.IDAVResourceWalkHandler.CallType; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVResourceWalker { public static final int DAV_WALKTYPE_AUTH = 0x0001; public static final int DAV_WALKTYPE_NORMAL = 0x0002; public static final int DAV_WALKTYPE_LOCKNULL = 0x0004; private LinkedList myIfHeaders; private DAVResource myResource; private DAVLockInfoProvider myLockInfoProvider; private DAVLockScope myLockScope; private int myFlags; private int myWalkType; private FSRoot myRoot; public DAVResponse walk(DAVLockInfoProvider lockInfoProvider, DAVResource resource, LinkedList ifHeaders, int flags, DAVLockScope lockScope, int walkType, IDAVResourceWalkHandler handler, DAVDepth depth) throws DAVException { myIfHeaders = ifHeaders; myLockInfoProvider = lockInfoProvider; myResource = resource.dup(); myFlags = flags; myWalkType = walkType; myRoot = resource.getRoot(); myLockScope = lockScope; return doWalk(handler, null, depth); } private DAVResponse doWalk(IDAVResourceWalkHandler handler, DAVResponse response, DAVDepth depth) throws DAVException { boolean isDir = myResource.isCollection(); response = handler.handleResource(response, myResource, myLockInfoProvider, myIfHeaders, myFlags, myLockScope, isDir ? CallType.COLLECTION : CallType.MEMBER); if (depth == DAVDepth.DEPTH_ZERO || !isDir) { return response; } if (myResource.isWorking()) { return response; } if (myResource.getType() != DAVResourceType.REGULAR) { throw new DAVException("Walking the resource hierarchy can only be done on 'regular' resources [at this time].", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } //TODO: log here that we are listing a dir myResource.setExists(true); myResource.setCollection(false); FSRevisionNode node = null; Map children = null; try { node = myRoot.getRevisionNode(myResource.getResourceURI().getPath()); children = node.getDirEntries(myRoot.getOwner()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not fetch collection members", null); } for (Iterator childrenIter = children.keySet().iterator(); childrenIter.hasNext(); ) { String childName = (String) childrenIter.next(); FSEntry childEntry = (FSEntry) children.get(childName); if ((myWalkType & DAV_WALKTYPE_AUTH) != 0) { // } String uriPath = myResource.getResourceURI().getURI(); String reposPath = myResource.getResourceURI().getPath(); myResource.getResourceURI().setURI(SVNPathUtil.append(uriPath, childName)); myResource.getResourceURI().setPath(SVNPathUtil.append(reposPath, childName)); if (childEntry.getType() == SVNNodeKind.FILE) { response = handler.handleResource(response, myResource, myLockInfoProvider, myIfHeaders, myFlags, myLockScope, CallType.MEMBER); } else { myResource.setCollection(true); try { response = doWalk(handler, response, DAVDepth.decreaseDepth(depth)); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not decrease depth", null); } myResource.setCollection(false); } myResource.getResourceURI().setURI(uriPath); myResource.getResourceURI().setPath(reposPath); } return response; } } DAVResponse.java000066400000000000000000000030031177510526000354470ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; /** * @version 1.1.2 * @author TMate Software Ltd. */ public class DAVResponse { private DAVResponse myNextResponse; private DAVPropsResult myPropResult; private int myStatusCode; private String myDescription; private String myHref; public DAVResponse(String description, String href, DAVResponse nextResponse, DAVPropsResult propResult, int statusCode) { myDescription = description; myHref = href; myNextResponse = nextResponse; myStatusCode = statusCode; myPropResult = propResult; } public DAVResponse getNextResponse() { return myNextResponse; } public int getStatusCode() { return myStatusCode; } public String getDescription() { return myDescription; } public String getHref() { return myHref; } public DAVPropsResult getPropResult() { return myPropResult; } } DAVUnlockHandler.java000066400000000000000000000052461177510526000364150ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPHeader; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceState; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVUnlockHandler extends ServletDAVHandler { protected DAVUnlockHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response) { super(repositoryManager, request, response); } public void execute() throws SVNException { String lockToken = getRequestHeader(HTTPHeader.LOCK_TOKEN_HEADER); if (lockToken == null) { sendError(HttpServletResponse.SC_BAD_REQUEST, "Unlock failed: No Lock-Token specified in header"); return; } if (lockToken.indexOf('<') == -1) { sendError(HttpServletResponse.SC_BAD_REQUEST, "Unlock failed: Malformed Lock-Token header"); return; } lockToken = lockToken.substring(1); if (lockToken.charAt(lockToken.length() - 1) != '>') { sendError(HttpServletResponse.SC_BAD_REQUEST, "Unlock failed: Malformed Lock-Token header"); return; } lockToken = lockToken.substring(0, lockToken.length() - 1); DAVResource resource = getRequestedDAVResource(false, false); DAVResourceState resourceState = getResourceState(resource); validateRequest(resource, DAVDepth.DEPTH_ZERO, resourceState == DAVResourceState.LOCK_NULL ? ServletDAVHandler.DAV_VALIDATE_PARENT : ServletDAVHandler.DAV_VALIDATE_RESOURCE, null, lockToken, null); unlock(resource, lockToken); setResponseStatus(HttpServletResponse.SC_NO_CONTENT); } protected DAVRequest getDAVRequest() { return null; } } DAVUnlockWalker.java000066400000000000000000000031551177510526000362620ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.LinkedList; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVUnlockWalker implements IDAVResourceWalkHandler { private ServletDAVHandler myServletHandler; private String myLockToken; public DAVUnlockWalker(String lockToken, ServletDAVHandler servletHandler) { myLockToken = lockToken; myServletHandler = servletHandler; } public DAVResponse handleResource(DAVResponse response, DAVResource resource, DAVLockInfoProvider lockInfoProvider, LinkedList ifHeaders, int flags, DAVLockScope lockScope, CallType callType) throws DAVException { if (resource.isWorking()) { myServletHandler.autoCheckIn(resource, false, true, null); } lockInfoProvider.removeLock(resource, myLockToken); return null; } } DAVUpdateHandler.java000066400000000000000000000745761177510526000364200ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTranslateReporter; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceKind; import org.tmatesoft.svn.core.internal.server.dav.DAVServletUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNHashSet; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNXMLUtil; import org.tmatesoft.svn.core.internal.wc.SVNAdminDeltifier; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.io.diff.SVNDiffWindow; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.Attributes; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVUpdateHandler extends DAVReportHandler implements ISVNEditor { private static Set UPDATE_REPORT_NAMESPACES = new SVNHashSet(); private static final DAVElement ENTRY = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "entry"); private static final DAVElement MISSING = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "missing"); private DAVUpdateRequest myDAVRequest; private FSTranslateReporter myReporter; private boolean myInitialized = false; private boolean myResourceWalk = false; private FSRepository mySourceRepository; private FSRevisionRoot myRevisionRoot; private long myRevision = DAVResource.INVALID_REVISION; private SVNURL myDstURL = null; private String myDstPath = null; private String myAnchor = null; private SVNDepth myDepth = SVNDepth.UNKNOWN; private SVNDepth myRequestedDepth = SVNDepth.UNKNOWN; private Map myPathMap = null; private long myEntryRevision = DAVResource.INVALID_REVISION; private String myEntryLinkPath = null; private boolean myEntryStartEmpty = false; private String myEntryLockToken = null; private String myFileBaseChecksum = null; private boolean myFileTextChanged = false; private EditorEntry myFileEditorEntry; private DAVReportHandler myCommonReportHandler; Stack myEditorEntries; static { UPDATE_REPORT_NAMESPACES.add(DAVElement.SVN_NAMESPACE); UPDATE_REPORT_NAMESPACES.add(DAVElement.SVN_DAV_PROPERTY_NAMESPACE); } public DAVUpdateHandler(DAVRepositoryManager repositoryManager, HttpServletRequest request, HttpServletResponse response, DAVReportHandler commonReportHandler) { super(repositoryManager, request, response); setSVNDiffVersion(getSVNDiffVersion()); myCommonReportHandler = commonReportHandler; } public DAVRequest getDAVRequest() { return getUpdateRequest(); } private DAVUpdateRequest getUpdateRequest() { if (myDAVRequest == null) { myDAVRequest = new DAVUpdateRequest(); } return myDAVRequest; } private FSTranslateReporter getReporter() { return myReporter; } private void setReporter(FSTranslateReporter reporter) { myReporter = reporter; } private long getRevision() { return myRevision; } private void setRevision(long revision) { myRevision = revision; } private SVNURL getDstURL() { return myDstURL; } private void setDstURL(SVNURL dstURL) { myDstURL = dstURL; } private String getDstPath() { return myDstPath; } private void setDstPath(String dstPath) { myDstPath = dstPath; } private String getAnchor() { return myAnchor; } private void setAnchor(String anchor) { myAnchor = anchor; } private SVNDepth getDepth() { return myDepth; } private void setDepth(SVNDepth depth) { myDepth = depth; } private Map getPathMap() { if (myPathMap == null) { myPathMap = new SVNHashMap(); } return myPathMap; } private void addToPathMap(String path, String linkPath) { String normalizedPath = DAVPathUtil.normalize(path); String repositoryPath = linkPath == null ? normalizedPath : linkPath; getPathMap().put(SVNPathUtil.getAbsolutePath(path), repositoryPath); } private boolean isInitialized() { return myInitialized; } private void setInitialized(boolean initialized) { myInitialized = initialized; } private boolean isResourceWalk() { return myResourceWalk; } private void setResourceWalk(boolean resourceWalk) { myResourceWalk = resourceWalk; } private FSRepository getSourceRepository() { return mySourceRepository; } private void setSourceRepository(FSRepository sourceRepository) { mySourceRepository = sourceRepository; } private long getEntryRevision() { return myEntryRevision; } private void setEntryRevision(long entryRevision) { myEntryRevision = entryRevision; } private String getEntryLinkPath() { return myEntryLinkPath; } private void setEntryLinkPath(String entryLinkPath) { myEntryLinkPath = entryLinkPath; } private boolean isEntryStartEmpty() { return myEntryStartEmpty; } private void setEntryStartEmpty(boolean entryStartEmpty) { myEntryStartEmpty = entryStartEmpty; } private String getEntryLockToken() { return myEntryLockToken; } private void setEntryLockToken(String entryLockToken) { myEntryLockToken = entryLockToken; } private String getFileBaseChecksum() { return myFileBaseChecksum; } private void setFileBaseChecksum(String fileBaseChecksum) { myFileBaseChecksum = fileBaseChecksum; } private boolean isFileTextChanged() { return myFileTextChanged; } private void setFileTextChanged(boolean fileTextChanged) { myFileTextChanged = fileTextChanged; } private void setFileIsAdded(boolean isAdded) { if (myFileEditorEntry == null) { myFileEditorEntry = new EditorEntry(isAdded); } else { myFileEditorEntry.setAdded(isAdded); } } private EditorEntry getFileEditorEntry() { return myFileEditorEntry; } private Stack getEditorEntries() { if (myEditorEntries == null) { myEditorEntries = new Stack(); } return myEditorEntries; } private void initialize() throws SVNException { if (!isInitialized()) { getUpdateRequest().init(); setDAVResource(getRequestedDAVResource(false, false)); long targetRevision = getUpdateRequest().getRevision(); if (!SVNRevision.isValidRevisionNumber(targetRevision)) { try { targetRevision = getDAVResource().getLatestRevision(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not determine the youngest revision for the update process.", null); } } setRevision(targetRevision); myRequestedDepth = getUpdateRequest().getDepth(); if (!getUpdateRequest().isDepthRequested() && !getUpdateRequest().isRecursiveRequested() && myRequestedDepth == SVNDepth.UNKNOWN) { myRequestedDepth = SVNDepth.INFINITY; } String srcPath = getRepositoryManager().getRepositoryRelativePath(getUpdateRequest().getSrcURL()); setAnchor(srcPath); SVNURL dstURL = getUpdateRequest().getDstURL(); String dstPath; if (dstURL != null) { dstPath = getRepositoryManager().getRepositoryRelativePath(dstURL); setDstPath(dstPath); setDstURL(getRepositoryManager().convertHttpToFile(dstURL)); addToPathMap(SVNPathUtil.getAbsolutePath(SVNPathUtil.append(srcPath, getUpdateRequest().getTarget())), dstPath); } FSFS fsfs = getDAVResource().getFSFS(); myRevisionRoot = fsfs.createRevisionRoot(targetRevision); SVNURL repositoryURL = getRepositoryManager().convertHttpToFile(getUpdateRequest().getSrcURL()); FSRepository repository = (FSRepository) SVNRepositoryFactory.create(repositoryURL); FSTranslateReporter reporter = repository.beginReport(getRevision(), getDstURL(), getUpdateRequest().getTarget(), getUpdateRequest().isIgnoreAncestry(), getUpdateRequest().isTextDeltas(), getUpdateRequest().isSendCopyFromArgs(), myRequestedDepth, this); setReporter(reporter); setSourceRepository(repository); setInitialized(true); } } protected void handleAttributes(DAVElement parent, DAVElement element, Attributes attrs) throws SVNException { if (element == ENTRY && parent == ServletDAVHandler.UPDATE_REPORT) { setEntryLinkPath(attrs.getValue(LINKPATH_ATTR)); setEntryLockToken(attrs.getValue(LOCK_TOKEN_ATTR)); String revisionString = attrs.getValue(REVISION_ATTR); if (revisionString == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Missing XML attribute: rev"), SVNLogType.NETWORK); } try { setEntryRevision(Long.parseLong(revisionString)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } setDepth(SVNDepth.fromString(attrs.getValue(DEPTH_ATTR))); if (attrs.getValue(START_EMPTY_ATTR) != null) { setEntryStartEmpty(true); } } else if (element != MISSING || parent != ServletDAVHandler.UPDATE_REPORT) { if (isInitialized()) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Invalid XML elements order: entry elements should follow any other."), SVNLogType.NETWORK); } getDAVRequest().startElement(parent, element, attrs); } } protected void handleCData(DAVElement parent, DAVElement element, StringBuffer cdata) throws SVNException { if (element == ENTRY && parent == ServletDAVHandler.UPDATE_REPORT) { handleEntry(cdata.toString(), false); } else if (element == MISSING && parent == ServletDAVHandler.UPDATE_REPORT) { handleEntry(cdata.toString(), true); } else { getDAVRequest().endElement(parent, element, cdata); } } private void handleEntry(String entryPath, boolean deletePath) throws SVNException { initialize(); try { if (deletePath) { getReporter().deletePath(entryPath); } else { if (getEntryLinkPath() == null) { getReporter().setPath(entryPath, getEntryLockToken(), getEntryRevision(), getDepth(), isEntryStartEmpty()); } else { SVNURL linkURL = getDAVResource().getRepository().getLocation().appendPath(getEntryLinkPath(), true); getReporter().linkPath(linkURL, entryPath, getEntryLockToken(), getEntryRevision(), getDepth(), isEntryStartEmpty()); } if (getEntryLinkPath() != null && getDstPath() == null) { String path = SVNPathUtil.append(getAnchor(), SVNPathUtil.append(getUpdateRequest().getTarget(), entryPath)); addToPathMap(path, getEntryLinkPath()); } refreshEntry(); } } catch (SVNException e) { getReporter().abortReport(); getReporter().closeRepository(); throw e; } } private void refreshEntry() { setEntryLinkPath(null); setEntryLockToken(null); setEntryRevision(DAVResource.INVALID_REVISION); setEntryStartEmpty(false); } private String getRealPath(String path) { path = SVNPathUtil.getAbsolutePath(SVNPathUtil.append(getAnchor(), path)); if (getPathMap().isEmpty()) { return path; } String repositoryPath = (String) getPathMap().get(path); if (repositoryPath != null) { return repositoryPath; } String tmpPath = path; do { tmpPath = SVNPathUtil.removeTail(tmpPath); repositoryPath = (String) getPathMap().get(tmpPath); if (repositoryPath != null) { return SVNPathUtil.append(repositoryPath, path.substring(tmpPath.length())); } } while (SVNPathUtil.getSegmentsCount(tmpPath) > 0); return path; } public void execute() throws SVNException { myCommonReportHandler.checkSVNNamespace("The request does not contain the 'svn:' namespace, so it is not going to have" + " an svn:target-revision element. That element is required."); writeXMLHeader(null); try { getReporter().finishReport(); } catch (SVNException e) { getReporter().abortReport(); throw e; } finally { getReporter().closeRepository(); } if (getDstPath() != null && getUpdateRequest().isResourceWalk()) { if (SVNNodeKind.DIR == getDAVResource().getRepository().checkPath(getDstPath(), getRevision())) { setResourceWalk(true); } } if (isResourceWalk()) { StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "resource-walk", SVNXMLUtil.XML_STYLE_NORMAL, null, null); write(xmlBuffer); FSFS fsfs = getSourceRepository().getFSFS(); SVNAdminDeltifier deltifier = new SVNAdminDeltifier(fsfs, myRequestedDepth, true, false, false, this); FSRevisionRoot zeroRoot = fsfs.createRevisionRoot(0); FSRevisionRoot requestedRoot = fsfs.createRevisionRoot(getRevision()); deltifier.deltifyDir(zeroRoot, "", getUpdateRequest().getTarget(), requestedRoot, getDstPath()); xmlBuffer = SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "resource-walk", null); write(xmlBuffer); } writeXMLFooter(null); } protected void addXMLHeader(StringBuffer xmlBuffer, String tagName) { Map attrs = new SVNHashMap(); if (getUpdateRequest().isSendAll()) { attrs.put(SEND_ALL_ATTR, Boolean.TRUE.toString()); } DAVElementProperty rootElement = getDAVRequest().getRootElement(); SVNXMLUtil.addXMLHeader(xmlBuffer); tagName = tagName == null ? rootElement.getName().getName() : tagName; DAVXMLUtil.openNamespaceDeclarationTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, UPDATE_REPORT_NAMESPACES, attrs, xmlBuffer, true, false); } public void targetRevision(long revision) throws SVNException { if (!isResourceWalk()) { StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "target-revision", SVNXMLUtil.XML_STYLE_SELF_CLOSING, REVISION_ATTR, String.valueOf(revision), null); write(xmlBuffer); } } public void openRoot(long revision) throws SVNException { EditorEntry entry = new EditorEntry(false); getEditorEntries().push(entry); StringBuffer xmlBuffer = null; if (isResourceWalk()) { xmlBuffer = openResourceTag("", xmlBuffer); } else { xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "open-directory", SVNXMLUtil.XML_STYLE_NORMAL, REVISION_ATTR, String.valueOf(revision), null); } if (getUpdateRequest().getTarget().length() == 0) { addVersionURL(getRealPath(""), xmlBuffer); } if (isResourceWalk()) { closeResourceTag(xmlBuffer); } write(xmlBuffer); } public void deleteEntry(String path, long revision) throws SVNException { writeEntryTag("delete-entry", path); } public void absentDir(String path) throws SVNException { if (!isResourceWalk()) { writeEntryTag("absent-directory", path); } } public void absentFile(String path) throws SVNException { if (!isResourceWalk()) { writeEntryTag("absent-file", path); } } public void addDir(String path, String copyFromPath, long copyFromRevision) throws SVNException { EditorEntry directoryEntry = new EditorEntry(true); getEditorEntries().push(directoryEntry); writeAddEntryTag(true, path, copyFromPath, copyFromRevision); } public void openDir(String path, long revision) throws SVNException { EditorEntry directoryEntry = new EditorEntry(false); getEditorEntries().push(directoryEntry); writeEntryTag("open-directory", path, revision); } public void changeDirProperty(String name, SVNPropertyValue value) throws SVNException { if (!isResourceWalk()) { EditorEntry entry = (EditorEntry) getEditorEntries().peek(); changeProperties(entry, name, value); } } public void closeDir() throws SVNException { EditorEntry entry = (EditorEntry) getEditorEntries().pop(); closeEntry(entry, true, null); } public void addFile(String path, String copyFromPath, long copyFromRevision) throws SVNException { setFileIsAdded(true); writeAddEntryTag(false, path, copyFromPath, copyFromRevision); } public void openFile(String path, long revision) throws SVNException { setFileIsAdded(false); writeEntryTag("open-file", path, revision); } public void changeFileProperty(String path, String name, SVNPropertyValue value) throws SVNException { if (!isResourceWalk()) { changeProperties(getFileEditorEntry(), name, value); } } public void closeFile(String path, String textChecksum) throws SVNException { if (!getUpdateRequest().isSendAll() && !getFileEditorEntry().isAdded() && isFileTextChanged()) { StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "fetch-file", SVNXMLUtil.XML_STYLE_SELF_CLOSING, BASE_CHECKSUM_ATTR, getFileBaseChecksum(), null); write(xmlBuffer); } closeEntry(getFileEditorEntry(), false, textChecksum); getFileEditorEntry().refresh(); setFileTextChanged(false); setFileBaseChecksum(null); } public SVNCommitInfo closeEdit() throws SVNException { return null; } public void abortEdit() throws SVNException { } public void applyTextDelta(String path, String baseChecksum) throws SVNException { setFileTextChanged(true); setFileBaseChecksum(baseChecksum); if (isResourceWalk()) { return; } StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "txdelta", SVNXMLUtil.XML_STYLE_NORMAL, null, null); write(xmlBuffer); } public OutputStream textDeltaChunk(String path, SVNDiffWindow diffWindow) throws SVNException { if (!isResourceWalk()) { writeTextDeltaChunk(diffWindow); } return null; } public void textDeltaEnd(String path) throws SVNException { if (!isResourceWalk()) { textDeltaChunkEnd(); setWriteTextDeltaHeader(true); StringBuffer xmlBuffer = SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "txdelta", null); write(xmlBuffer); } } private StringBuffer openResourceTag(String path, StringBuffer xmlBuffer) { return SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "resource", SVNXMLUtil.XML_STYLE_NORMAL, PATH_ATTR, path, xmlBuffer); } private StringBuffer closeResourceTag(StringBuffer xmlBuffer) { return SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "resource", xmlBuffer); } private void writeEntryTag(String tagName, String path) throws SVNException { String directoryName = SVNPathUtil.tail(path); StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_SELF_CLOSING, NAME_ATTR, directoryName, null); write(xmlBuffer); } private void writeEntryTag(String tagName, String path, long revision) throws SVNException { Map attrs = new SVNHashMap(); attrs.put(NAME_ATTR, SVNPathUtil.tail(path)); attrs.put(REVISION_ATTR, String.valueOf(revision)); StringBuffer xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_NORMAL, attrs, null); addVersionURL(getRealPath(path), xmlBuffer); write(xmlBuffer); } private void writeAddEntryTag(boolean isDirectory, String path, String copyFromPath, long copyFromRevision) throws SVNException { StringBuffer xmlBuffer = null; String realPath = getRealPath(path); if (isResourceWalk()) { String resourcePath = getUpdateRequest().getTarget() == null || getUpdateRequest().getTarget().length() == 0 ? path : SVNPathUtil.append(getUpdateRequest().getTarget(), SVNPathUtil.removeHead(path)); xmlBuffer = openResourceTag(resourcePath, xmlBuffer); } else { Map attrs = new SVNHashMap(); attrs.put(NAME_ATTR, SVNPathUtil.tail(path)); if (isDirectory) { long createdRevision = DAVServletUtil.getSafeCreatedRevision(myRevisionRoot, realPath); String bcURL = DAVPathUtil.buildURI(getDAVResource().getResourceURI().getContext(), DAVResourceKind.BASELINE_COLL, createdRevision, realPath, false); attrs.put(BC_URL_ATTR, bcURL); } if (copyFromPath != null) { attrs.put(COPYFROM_PATH_ATTR, copyFromPath); attrs.put(COPYFROM_REVISION_ATTR, String.valueOf(copyFromRevision)); } String tagName = isDirectory ? "add-directory" : "add-file"; xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, SVNXMLUtil.XML_STYLE_NORMAL, attrs, null); } addVersionURL(realPath, xmlBuffer); if (isResourceWalk()) { closeResourceTag(xmlBuffer); } write(xmlBuffer); } private void changeProperties(EditorEntry entry, String name, SVNPropertyValue value) throws SVNException { //String quotedName = SVNEncodingUtil.xmlEncodeCDATA(name, true); if (getUpdateRequest().isSendAll()) { if (value != null) { writePropertyTag("set-prop", name, value); } else { writeEntryTag("remove-prop", name); } } else { if (SVNProperty.isEntryProperty(name)) { if (SVNProperty.COMMITTED_REVISION.equals(name)) { entry.setCommitedRevision(value.getString()); } else if (SVNProperty.COMMITTED_DATE.equals(name)) { entry.setCommitedDate(value.getString()); } else if (SVNProperty.LAST_AUTHOR.equals(name)) { entry.setLastAuthor(value.getString()); } else if (SVNProperty.LOCK_TOKEN.equals(name) && value == null) { entry.addRemovedProperty(name); } return; } if (value == null) { entry.addRemovedProperty(name); } else { entry.setHasChangedProperty(true); } } } private void closeEntry(EditorEntry entry, boolean isDirectory, String textCheckSum) throws SVNException { if (isResourceWalk()) { return; } StringBuffer xmlBuffer = new StringBuffer(); if (!entry.removedPropertiesCollectionIsEmpty() && !entry.isAdded()) { for (Iterator iterator = entry.getRemovedProperies(); iterator.hasNext();) { String name = (String) iterator.next(); SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "remove-prop", SVNXMLUtil.XML_STYLE_SELF_CLOSING, NAME_ATTR, name, xmlBuffer); } } if (!getUpdateRequest().isSendAll() && entry.hasChangedProperties() && !entry.isAdded()) { SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "fetch-props", SVNXMLUtil.XML_STYLE_SELF_CLOSING, null, xmlBuffer); } SVNXMLUtil.openXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "prop", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); if (textCheckSum != null) { SVNXMLUtil.openCDataTag(SVNXMLUtil.SVN_DAV_PROPERTY_PREFIX, "md5-checksum", textCheckSum, xmlBuffer); } if (entry.getCommitedRevision() != null) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.VERSION_NAME.getName(), entry.getCommitedRevision(), xmlBuffer); } if (entry.getCommitedDate() != null) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.CREATION_DATE.getName(), entry.getCommitedDate(), xmlBuffer); } if (entry.getLastAuthor() != null) { SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, DAVElement.CREATOR_DISPLAY_NAME.getName(), entry.getLastAuthor(), xmlBuffer); } SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, "prop", xmlBuffer); String tagName = entry.isAdded() ? "add-" : "open-"; tagName += isDirectory ? "directory" : "file"; SVNXMLUtil.closeXMLTag(SVNXMLUtil.SVN_NAMESPACE_PREFIX, tagName, xmlBuffer); write(xmlBuffer); } private StringBuffer addVersionURL(String path, StringBuffer xmlBuffer) { long revision = DAVServletUtil.getSafeCreatedRevision(myRevisionRoot, path); String url = DAVPathUtil.buildURI(getDAVResource().getResourceURI().getContext(), DAVResourceKind.VERSION, revision, path, false); xmlBuffer = SVNXMLUtil.openXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "checked-in", SVNXMLUtil.XML_STYLE_NORMAL, null, xmlBuffer); SVNXMLUtil.openCDataTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "href", url, xmlBuffer); SVNXMLUtil.closeXMLTag(SVNXMLUtil.DAV_NAMESPACE_PREFIX, "checked-in", xmlBuffer); return xmlBuffer; } private class EditorEntry { boolean myAdded = false; private String myCommitedRevision = null; private String myCommitedDate = null; private String myLastAuthor = null; private Collection myRemovedProperties; boolean myHasChangedProperties = false; public EditorEntry(boolean isAdded) { myAdded = isAdded; } private void setAdded(boolean isAdded) { myAdded = isAdded; } private boolean isAdded() { return myAdded; } private void setHasChangedProperty(boolean hasChangedProperties) { myHasChangedProperties = hasChangedProperties; } private boolean hasChangedProperties() { return myHasChangedProperties; } private void addRemovedProperty(String name) { if (myRemovedProperties == null) { myRemovedProperties = new ArrayList(); } myRemovedProperties.add(name); } private boolean removedPropertiesCollectionIsEmpty() { return myRemovedProperties == null || myRemovedProperties.isEmpty(); } private Iterator getRemovedProperies() { if (!removedPropertiesCollectionIsEmpty()) { return myRemovedProperties.iterator(); } return null; } private String getCommitedRevision() { return myCommitedRevision; } private void setCommitedRevision(String commitedRevision) { myCommitedRevision = commitedRevision; } private String getCommitedDate() { return myCommitedDate; } private void setCommitedDate(String commitedDate) { myCommitedDate = commitedDate; } private String getLastAuthor() { return myLastAuthor; } private void setLastAuthor(String lastAuthor) { myLastAuthor = lastAuthor; } private void refresh() { myCommitedRevision = null; myCommitedDate = null; myLastAuthor = null; myHasChangedProperties = false; if (myRemovedProperties != null) { myRemovedProperties.clear(); } } } } DAVUpdateRequest.java000066400000000000000000000215401177510526000364520ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.2.0 */ public class DAVUpdateRequest extends DAVRequest { private static final DAVElement TARGET_REVISION = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "target-revision"); private static final DAVElement SRC_PATH = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "src-path"); private static final DAVElement DST_PATH = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "dst-path"); private static final DAVElement UPDATE_TARGET = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "update-target"); private static final DAVElement DEPTH = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "depth"); private static final DAVElement RECURSIVE = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "recursive"); private static final DAVElement SEND_COPYFROM_ARGS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "send-copyfrom-args"); private static final DAVElement IGNORE_ANCESTRY = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "ignore-ancestry"); private static final DAVElement TEXT_DELTAS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "text-deltas"); private static final DAVElement RESOURCE_WALK = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "resource-walk"); private boolean mySendAll = false; private long myRevision = DAVResource.INVALID_REVISION; private SVNURL mySrcURL = null; private SVNURL myDstURL = null; private String myTarget = ""; private boolean myTextDeltas = true; private SVNDepth myDepth = SVNDepth.UNKNOWN; private boolean mySendCopyFromArgs = false; private boolean myDepthRequested = false; private boolean myRecursiveRequested = false; private boolean myIgnoreAncestry = false; private boolean myResourceWalk = false; private boolean myIsInitialized; public boolean isSendAll() { return mySendAll; } private void setSendAll(boolean sendAll) { mySendAll = sendAll; } public long getRevision() { return myRevision; } private void setRevision(long revision) { myRevision = revision; } public SVNURL getSrcURL() { return mySrcURL; } private void setSrcURL(SVNURL srcURL) { mySrcURL = srcURL; } public SVNURL getDstURL() { return myDstURL; } private void setDstURL(SVNURL dstURL) { myDstURL = dstURL; } public String getTarget() { return myTarget; } private void setTarget(String target) { myTarget = target; } public boolean isTextDeltas() { return myTextDeltas; } private void setTextDeltas(boolean textDeltas) { myTextDeltas = textDeltas; } public SVNDepth getDepth() { return myDepth; } private void setDepth(SVNDepth depth) { myDepth = depth; } public boolean isSendCopyFromArgs() { return mySendCopyFromArgs; } private void setSendCopyFromArgs(boolean sendCopyFromArgs) { mySendCopyFromArgs = sendCopyFromArgs; } public boolean isDepthRequested() { return myDepthRequested; } private void setDepthRequested(boolean depthRequested) { myDepthRequested = depthRequested; } public boolean isRecursiveRequested() { return myRecursiveRequested; } private void setRecursiveRequested(boolean recursiveRequested) { myRecursiveRequested = recursiveRequested; } public boolean isIgnoreAncestry() { return myIgnoreAncestry; } private void setIgnoreAncestry(boolean ignoreAncestry) { myIgnoreAncestry = ignoreAncestry; } public boolean isResourceWalk() { return myResourceWalk; } private void setResourceWalk(boolean resourceWalk) { myResourceWalk = resourceWalk; } private boolean isInitialized() { return myIsInitialized; } private void setInitialized(boolean isInitialized) { myIsInitialized = isInitialized; } protected void init() throws SVNException { if (!isInitialized()) { String sendAll = getRootElementAttributeValue("send-all"); setSendAll(sendAll != null && Boolean.valueOf(sendAll).booleanValue()); DAVElementProperty rootElement = getRootElement(); for (Iterator iterator = rootElement.getChildren().iterator(); iterator.hasNext();) { DAVElementProperty property = (DAVElementProperty) iterator.next(); DAVElement element = property.getName(); if (element == TARGET_REVISION) { assertNullCData(element, property); String value = property.getFirstValue(true); try { setRevision(Long.parseLong(value)); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, nfe), SVNLogType.NETWORK); } } else if (element == SRC_PATH) { assertNullCData(element, property); String value = property.getFirstValue(false); DAVPathUtil.testCanonical(value); setSrcURL(SVNURL.parseURIEncoded(value)); } else if (element == DST_PATH) { assertNullCData(element, property); String value = property.getFirstValue(false); DAVPathUtil.testCanonical(value); setDstURL(SVNURL.parseURIEncoded(value)); } else if (element == UPDATE_TARGET) { String value = property.getFirstValue(false); DAVPathUtil.testCanonical(value); setTarget(value); } else if (element == DEPTH) { assertNullCData(element, property); String value = property.getFirstValue(true); setDepth(SVNDepth.fromString(value)); setDepthRequested(true); } else if (element == SEND_COPYFROM_ARGS) { assertNullCData(element, property); setSendCopyFromArgs("no".equals(property.getFirstValue(true))); } else if (element == RECURSIVE && !isDepthRequested()) { assertNullCData(element, property); String value = property.getFirstValue(true); setDepth(SVNDepth.fromRecurse(!"no".equals(value))); setRecursiveRequested(true); } else if (element == IGNORE_ANCESTRY) { assertNullCData(element, property); String value = property.getFirstValue(true); setIgnoreAncestry(!"no".equals(value)); } else if (element == TEXT_DELTAS) { assertNullCData(element, property); String value = property.getFirstValue(true); setTextDeltas(!"no".equals(value)); } else if (element == RESOURCE_WALK) { assertNullCData(element, property); String value = property.getFirstValue(true); setResourceWalk(!"no".equals(value)); } } if (!isDepthRequested() && !isRecursiveRequested() && (getDepth() == SVNDepth.UNKNOWN)) { setDepth(SVNDepth.INFINITY); } if (getSrcURL() == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "The request did not contain the '' element.\nThis may indicate that your client is too old."), SVNLogType.NETWORK); } if (!isSendAll()) { setTextDeltas(false); } setInitialized(true); } } } DAVValidateWalker.java000066400000000000000000000277051177510526000365670ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.Iterator; import java.util.LinkedList; import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVIFHeader; import org.tmatesoft.svn.core.internal.server.dav.DAVIFState; import org.tmatesoft.svn.core.internal.server.dav.DAVIFStateType; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVValidateWalker implements IDAVResourceWalkHandler { public DAVResponse handleResource(DAVResponse response, DAVResource resource, DAVLockInfoProvider lockInfoProvider, LinkedList ifHeaders, int flags, DAVLockScope lockScope, CallType callType) throws DAVException { DAVException exception = null; try { validateResourceState(ifHeaders, resource, lockInfoProvider, lockScope, flags); return response; } catch (DAVException e) { exception = e; } //TODO: I'm not sure what resources we should compare here if (DAVServlet.isHTTPServerError(exception.getResponseCode())) { throw exception; } DAVResponse resp = new DAVResponse(null, resource.getResourceURI().getRequestURI(), response, null, exception.getResponseCode()); return resp; } public void validateResourceState(LinkedList ifHeaders, DAVResource resource, DAVLockInfoProvider provider, DAVLockScope lockScope, int flags) throws DAVException { DAVLock lock = null; if (provider != null) { try { lock = provider.getLock(resource); } catch (DAVException dave) { throw new DAVException("The locks could not be queried for verification against a possible \"If:\" header.", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } } boolean seenLockToken = false; if (lockScope == DAVLockScope.EXCLUSIVE) { if (lock != null) { throw new DAVException("Existing lock(s) on the requested resource prevent an exclusive lock.", ServletDAVHandler.SC_HTTP_LOCKED, 0); } seenLockToken = true; } else if (lockScope == DAVLockScope.SHARED) { if (lock.getScope() == DAVLockScope.EXCLUSIVE) { throw new DAVException("The requested resource is already locked exclusively.", ServletDAVHandler.SC_HTTP_LOCKED, 0); } seenLockToken = true; } else { seenLockToken = lock == null; } if (ifHeaders == null || ifHeaders.isEmpty()) { if (seenLockToken) { return; } throw new DAVException("This resource is locked and an \"If:\" header was not supplied to allow access to the resource.", ServletDAVHandler.SC_HTTP_LOCKED, 0); } DAVIFHeader ifHeader = (DAVIFHeader) ifHeaders.getFirst(); if (lock == null && ifHeader.isDummyHeader()) { if ((flags & ServletDAVHandler.DAV_VALIDATE_IS_PARENT) != 0) { return; } throw new DAVException("The locktoken specified in the \"Lock-Token:\" header is invalid because this resource has no outstanding locks.", HttpServletResponse.SC_BAD_REQUEST, 0); } String eTag = resource.getETag(); String uri = DAVPathUtil.dropTraillingSlash(resource.getResourceURI().getRequestURI()); int numThatAppy = 0; String reason = null; Iterator ifHeadersIter = ifHeaders.iterator(); for (;ifHeadersIter.hasNext();) { ifHeader = (DAVIFHeader) ifHeadersIter.next(); if (ifHeader.getURI() != null && !uri.equals(ifHeader.getURI())) { continue; } ++numThatAppy; LinkedList stateList = ifHeader.getStateList(); boolean doContinue = false; for (Iterator stateListIter = stateList.iterator(); stateListIter.hasNext();) { DAVIFState state = (DAVIFState) stateListIter.next(); if (state.getType() == DAVIFStateType.IF_ETAG) { String currentETag = null; String givenETag = null; String stateETag = state.getETag(); if (stateETag.startsWith("W/")) { givenETag = stateETag.substring(2); } else { givenETag = stateETag; } if (eTag.startsWith("W/")) { currentETag = eTag.substring(2); } else { currentETag = eTag; } boolean eTagsDoNotMatch = !givenETag.equals(currentETag); if (state.getCondition() == DAVIFState.IF_CONDITION_NORMAL && eTagsDoNotMatch) { reason = "an entity-tag was specified, but the resource's actual ETag does not match."; doContinue = true; break; } else if (state.getCondition() == DAVIFState.IF_CONDITION_NOT && !eTagsDoNotMatch) { reason = "an entity-tag was specified using the \"Not\" form, but the resource's actual ETag matches the provided entity-tag."; doContinue = true; break; } } else if (state.getType() == DAVIFStateType.IF_OPAQUE_LOCK) { if (provider == null) { if (state.getCondition() == DAVIFState.IF_CONDITION_NOT) { continue; } reason = "a State-token was supplied, but a lock database is not available for to provide the required lock."; doContinue = true; break; } boolean matched = false; if (lock != null) { if (!lock.getLockToken().equals(state.getLockToken())) { continue; } seenLockToken = true; if (state.getCondition() == DAVIFState.IF_CONDITION_NOT) { reason = "a State-token was supplied, which used a \"Not\" condition. The State-token was found in the locks on this resource"; doContinue = true; break; } String lockAuthUser = lock.getAuthUser(); String requestUser = resource.getUserName(); if (lockAuthUser != null && (requestUser == null || !lockAuthUser.equals(requestUser))) { throw new DAVException("User \"{0}\" submitted a locktoken created by user \"{1}\".", new Object[] { requestUser, lockAuthUser }, HttpServletResponse.SC_FORBIDDEN, 0); } matched = true; } if (!matched && state.getCondition() == DAVIFState.IF_CONDITION_NORMAL) { reason = "a State-token was supplied, but it was not found in the locks on this resource."; doContinue = true; break; } } else if (state.getType() == DAVIFStateType.IF_UNKNOWN) { if (state.getCondition() == DAVIFState.IF_CONDITION_NORMAL) { reason = "an unknown state token was supplied"; doContinue = true; break; } } } if (doContinue) { continue; } if (seenLockToken) { return; } break; } if (!ifHeadersIter.hasNext()) { if (numThatAppy == 0) { if (seenLockToken) { return; } if (findSubmittedLockToken(ifHeaders, lock)) { return; } throw new DAVException("This resource is locked and the \"If:\" header did not specify one of the locktokens for this resource's lock(s).", ServletDAVHandler.SC_HTTP_LOCKED, 0); } ifHeader = (DAVIFHeader) ifHeaders.getFirst(); if (ifHeader.isDummyHeader()) { throw new DAVException("The locktoken specified in the \"Lock-Token:\" header did not specify one of this resource's locktoken(s).", HttpServletResponse.SC_BAD_REQUEST, 0); } if (reason == null) { throw new DAVException("The preconditions specified by the \"If:\" header did not match this resource.", HttpServletResponse.SC_PRECONDITION_FAILED, 0); } throw new DAVException("The precondition(s) specified by the \"If:\" header did not match this resource. At least one failure is because: {0}", new Object[] { reason }, HttpServletResponse.SC_PRECONDITION_FAILED, 0); } if (findSubmittedLockToken(ifHeaders, lock)) { return; } if (ifHeader.isDummyHeader()) { throw new DAVException("The locktoken specified in the \"Lock-Token:\" header did not specify one of this resource's locktoken(s).", HttpServletResponse.SC_BAD_REQUEST, 0); } throw new DAVException("This resource is locked and the \"If:\" header did not specify one of the locktokens for this resource's lock(s).", ServletDAVHandler.SC_HTTP_LOCKED, 1); } private boolean findSubmittedLockToken(LinkedList ifHeaders, DAVLock lock) { for (Iterator ifHeadersIter = ifHeaders.iterator(); ifHeadersIter.hasNext();) { DAVIFHeader ifHeader = (DAVIFHeader) ifHeadersIter.next(); LinkedList ifStates = ifHeader.getStateList(); for (Iterator ifStatesIter = ifStates.iterator(); ifStatesIter.hasNext();) { DAVIFState ifState = (DAVIFState) ifStatesIter.next(); if (ifState.getType() == DAVIFStateType.IF_OPAQUE_LOCK) { String lockToken = lock.getLockToken(); String stateLockToken = ifState.getLockToken(); if (lockToken.equals(stateLockToken)) { return true; } } } } return false; } } DAVWalkResource.java000066400000000000000000000012531177510526000362640ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class DAVWalkResource { } IDAVResourceWalkHandler.java000066400000000000000000000026321177510526000376750ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.util.LinkedList; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; /** * @version 1.2.0 * @author TMate Software Ltd. */ public interface IDAVResourceWalkHandler { public DAVResponse handleResource(DAVResponse response, DAVResource resource, DAVLockInfoProvider lockInfoProvider, LinkedList ifHeaders, int flags, DAVLockScope lockScope, CallType callType) throws DAVException; public static class CallType { public static final CallType MEMBER = new CallType(); public static final CallType COLLECTION = new CallType(); public static final CallType LOCKNULL = new CallType(); private CallType() { } } } LivePropertySpecification.java000066400000000000000000000024651177510526000404760ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; /** * @version 1.2.0 * @author TMate Software Ltd. */ public class LivePropertySpecification { private DAVElement myPropertyName; private boolean myIsWritable; private boolean myIsSVNSupported; public LivePropertySpecification(DAVElement propertyName, boolean isWritable, boolean isSVNSupported) { myIsWritable = isWritable; myPropertyName = propertyName; myIsSVNSupported = isSVNSupported; } public DAVElement getPropertyName() { return myPropertyName; } public boolean isWritable() { return myIsWritable; } public boolean isSVNSupported() { return myIsSVNSupported; } } ServletDAVHandler.java000066400000000000000000002617531177510526000366150ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/java/org/tmatesoft/svn/core/internal/server/dav/handlers/* * ==================================================================== * Copyright (c) 2004-2008 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.server.dav.handlers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.regex.Pattern; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.internal.delta.SVNDeltaReader; import org.tmatesoft.svn.core.internal.io.dav.DAVElement; import org.tmatesoft.svn.core.internal.io.dav.handlers.BasicDAVHandler; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPHeader; import org.tmatesoft.svn.core.internal.io.fs.FSCommitter; import org.tmatesoft.svn.core.internal.io.fs.FSDeltaConsumer; import org.tmatesoft.svn.core.internal.io.fs.FSFS; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionNode; import org.tmatesoft.svn.core.internal.io.fs.FSRevisionRoot; import org.tmatesoft.svn.core.internal.io.fs.FSRoot; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionInfo; import org.tmatesoft.svn.core.internal.io.fs.FSTransactionRoot; import org.tmatesoft.svn.core.internal.server.dav.DAVAutoVersion; import org.tmatesoft.svn.core.internal.server.dav.DAVConfig; import org.tmatesoft.svn.core.internal.server.dav.DAVDepth; import org.tmatesoft.svn.core.internal.server.dav.DAVException; import org.tmatesoft.svn.core.internal.server.dav.DAVIFHeader; import org.tmatesoft.svn.core.internal.server.dav.DAVIFState; import org.tmatesoft.svn.core.internal.server.dav.DAVIFStateType; import org.tmatesoft.svn.core.internal.server.dav.DAVLock; import org.tmatesoft.svn.core.internal.server.dav.DAVLockScope; import org.tmatesoft.svn.core.internal.server.dav.DAVPathUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVRepositoryManager; import org.tmatesoft.svn.core.internal.server.dav.DAVResource; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceHelper; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceKind; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceState; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceType; import org.tmatesoft.svn.core.internal.server.dav.DAVResourceURI; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; import org.tmatesoft.svn.core.internal.server.dav.DAVServletUtil; import org.tmatesoft.svn.core.internal.server.dav.DAVURIInfo; import org.tmatesoft.svn.core.internal.server.dav.DAVVersionResourceHelper; import org.tmatesoft.svn.core.internal.server.dav.DAVWorkingResourceHelper; import org.tmatesoft.svn.core.internal.server.dav.DAVXMLUtil; import org.tmatesoft.svn.core.internal.util.CountingInputStream; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashSet; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNUUIDGenerator; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.io.ISVNDeltaConsumer; import org.tmatesoft.svn.core.io.SVNCapability; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; import org.tmatesoft.svn.util.Version; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.tmatesoft.svn.core.internal.io.dav.http.XMLReader; /** * @author TMate Software Ltd. * @version 1.2.0 */ public abstract class ServletDAVHandler extends BasicDAVHandler { public static final int SC_MULTISTATUS = 207; public static final int SC_HTTP_LOCKED = 423; public static final int SC_FAILED_DEPENDANCY = 424; //some flag constants public static final int DAV_VALIDATE_RESOURCE = 0x0010; public static final int DAV_VALIDATE_PARENT = 0x0020; public static final int DAV_VALIDATE_ADD_LD = 0x0040; public static final int DAV_VALIDATE_USE_424 = 0x0080; public static final int DAV_VALIDATE_IS_PARENT = 0x0100; public static final int DAV_MODE_WRITE_TRUNC = 0; public static final int DAV_MODE_WRITE_SEEKABLE = 1; protected static final String CAPABILITY_YES = "yes"; protected static final String CAPABILITY_NO = "no"; protected static final String HTTP_STATUS_OK_LINE = "HTTP/1.1 200 OK"; protected static final String HTTP_NOT_FOUND_LINE = "HTTP/1.1 404 NOT FOUND"; protected static final String DAV_RESPONSE_BODY_1 = "\n\n"; protected static final String DAV_RESPONSE_BODY_2 = "\n\n

"; protected static final String DAV_RESPONSE_BODY_3 = "

\n

"; protected static final String DAV_RESPONSE_BODY_4 = "

\n"; protected static final String DAV_RESPONSE_BODY_5 = "\n"; protected static final String DEFAULT_XML_CONTENT_TYPE = "text/xml; charset=\"utf-8\""; protected static final String UTF8_ENCODING = "UTF-8"; protected static final String BASE64_ENCODING = "base64"; //Specific svn headers protected static final String SVN_OPTIONS_HEADER = "X-SVN-Options"; protected static final String SVN_DELTA_BASE_HEADER = "X-SVN-VR-Base"; protected static final String SVN_VERSION_NAME_HEADER = "X-SVN-Version-Name"; protected static final String SVN_CREATIONDATE_HEADER = "X-SVN-Creation-Date"; protected static final String SVN_LOCK_OWNER_HEADER = "X-SVN-Lock-Owner"; protected static final String SVN_BASE_FULLTEXT_MD5_HEADER = "X-SVN-Base-Fulltext-MD5"; protected static final String SVN_RESULT_FULLTEXT_MD5_HEADER = "X-SVN-Result-Fulltext-MD5"; //Precondition headers protected static final String IF_MATCH_HEADER = "If-Match"; protected static final String IF_UNMODIFIED_SINCE_HEADER = "If-Unmodified-Since"; protected static final String IF_NONE_MATCH_HEADER = "If-None-Match"; protected static final String IF_MODIFIED_SINCE_HEADER = "If-Modified-Since"; protected static final String ETAG_HEADER = "ETag"; protected static final String RANGE_HEADER = "Range"; //Common HTTP headers protected static final String DEPTH_HEADER = "Depth"; protected static final String VARY_HEADER = "Vary"; protected static final String LAST_MODIFIED_HEADER = "Last-Modified"; protected static final String LABEL_HEADER = "Label"; protected static final String USER_AGENT_HEADER = "User-Agent"; protected static final String CONNECTION_HEADER = "Connection"; protected static final String DATE_HEADER = "Date"; protected static final String KEEP_ALIVE_HEADER = "Keep-Alive"; protected static final String ACCEPT_RANGES_HEADER = "Accept-Ranges"; protected static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; protected static final String CACHE_CONTROL_HEADER = "Cache-Control"; //Common xml attributes protected static final String NAME_ATTR = "name"; protected static final String ENCODING_ATTR = "encoding"; protected static final String NAMESPACE_ATTR = "namespace"; protected static final String DIFF_VERSION_1 = "svndiff1"; protected static final String DIFF_VERSION = "svndiff"; protected static final String ACCEPT_RANGES_DEFAULT_VALUE = "bytes"; protected static final String CACHE_CONTROL_VALUE = "no-cache"; private static final Pattern COMMA = Pattern.compile(","); //Report related stuff DAVOptionsHandler uses protected static Set REPORT_ELEMENTS = new SVNHashSet(); protected static final DAVElement UPDATE_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "update-report"); protected static final DAVElement LOG_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "log-report"); protected static final DAVElement DATED_REVISIONS_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "dated-rev-report"); protected static final DAVElement GET_LOCATIONS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "get-locations"); protected static final DAVElement GET_LOCATION_SEGMENTS = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "get-location-segments"); protected static final DAVElement FILE_REVISIONS_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "file-revs-report"); protected static final DAVElement GET_LOCKS_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "get-locks-report"); protected static final DAVElement REPLAY_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "replay-report"); protected static final DAVElement MERGEINFO_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "mergeinfo-report"); protected static final DAVElement GET_DELETED_REVISION_REPORT = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "get-deleted-rev-report"); protected static final DAVElement LOCK_PATH_ELEM = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "lock-path"); protected static final DAVElement LOCK_TOKEN_ELEM = DAVElement.getElement(DAVElement.SVN_NAMESPACE, "lock-token"); private static SAXParserFactory ourSAXParserFactory; private SAXParser mySAXParser; private DAVRepositoryManager myRepositoryManager; private HttpServletRequest myRequest; private HttpServletResponse myResponse; private FSCommitter myCommitter; private FSDeltaConsumer myDeltaConsumer; static { REPORT_ELEMENTS.add(UPDATE_REPORT); REPORT_ELEMENTS.add(LOG_REPORT); REPORT_ELEMENTS.add(DATED_REVISIONS_REPORT); REPORT_ELEMENTS.add(GET_LOCATIONS); REPORT_ELEMENTS.add(FILE_REVISIONS_REPORT); REPORT_ELEMENTS.add(GET_LOCKS_REPORT); REPORT_ELEMENTS.add(REPLAY_REPORT); REPORT_ELEMENTS.add(MERGEINFO_REPORT); } protected static final Map OUR_LIVE_PROPS = new HashMap(); protected static final Map OUR_CORE_LIVE_PROPS = new HashMap(); static { OUR_LIVE_PROPS.put(DAVElement.GET_CONTENT_LENGTH, new LivePropertySpecification(DAVElement.GET_CONTENT_LENGTH, false, true)); OUR_LIVE_PROPS.put(DAVElement.GET_CONTENT_TYPE, new LivePropertySpecification(DAVElement.GET_CONTENT_TYPE, false, true)); OUR_LIVE_PROPS.put(DAVElement.GET_ETAG, new LivePropertySpecification(DAVElement.GET_ETAG, false, true)); OUR_LIVE_PROPS.put(DAVElement.CREATION_DATE, new LivePropertySpecification(DAVElement.CREATION_DATE, false, true)); OUR_LIVE_PROPS.put(DAVElement.GET_LAST_MODIFIED, new LivePropertySpecification(DAVElement.GET_LAST_MODIFIED, false, true)); OUR_LIVE_PROPS.put(DAVElement.BASELINE_COLLECTION, new LivePropertySpecification(DAVElement.BASELINE_COLLECTION, false, true)); OUR_LIVE_PROPS.put(DAVElement.CHECKED_IN, new LivePropertySpecification(DAVElement.CHECKED_IN, false, true)); OUR_LIVE_PROPS.put(DAVElement.VERSION_CONTROLLED_CONFIGURATION, new LivePropertySpecification(DAVElement.VERSION_CONTROLLED_CONFIGURATION, false, true)); OUR_LIVE_PROPS.put(DAVElement.VERSION_NAME, new LivePropertySpecification(DAVElement.VERSION_NAME, false, true)); OUR_LIVE_PROPS.put(DAVElement.CREATOR_DISPLAY_NAME, new LivePropertySpecification(DAVElement.CREATOR_DISPLAY_NAME, false, true)); OUR_LIVE_PROPS.put(DAVElement.AUTO_VERSION, new LivePropertySpecification(DAVElement.AUTO_VERSION, false, true)); OUR_LIVE_PROPS.put(DAVElement.BASELINE_RELATIVE_PATH, new LivePropertySpecification(DAVElement.BASELINE_RELATIVE_PATH, false, true)); OUR_LIVE_PROPS.put(DAVElement.MD5_CHECKSUM, new LivePropertySpecification(DAVElement.MD5_CHECKSUM, false, true)); OUR_LIVE_PROPS.put(DAVElement.REPOSITORY_UUID, new LivePropertySpecification(DAVElement.REPOSITORY_UUID, false, true)); OUR_LIVE_PROPS.put(DAVElement.DEADPROP_COUNT, new LivePropertySpecification(DAVElement.DEADPROP_COUNT, false, true)); //TODO: this probably should be later moved to CORE_LIVE_PROPS and shouldn't be actually SVN supported OUR_LIVE_PROPS.put(DAVElement.COMMENT, new LivePropertySpecification(DAVElement.COMMENT, true, true)); OUR_LIVE_PROPS.put(DAVElement.DISPLAY_NAME, new LivePropertySpecification(DAVElement.DISPLAY_NAME, true, true)); OUR_LIVE_PROPS.put(DAVElement.RESOURCE_TYPE, new LivePropertySpecification(DAVElement.RESOURCE_TYPE, false, true)); OUR_LIVE_PROPS.put(DAVElement.SOURCE, new LivePropertySpecification(DAVElement.SOURCE, true, true)); //TODO: the following three props are supported by DAV itself, should we do that as well? OUR_CORE_LIVE_PROPS.put(DAVElement.GET_CONTENT_TYPE, new LivePropertySpecification(DAVElement.GET_CONTENT_TYPE, false, false)); OUR_CORE_LIVE_PROPS.put(DAVElement.GET_CONTENT_LANGUAGE, new LivePropertySpecification(DAVElement.GET_CONTENT_LANGUAGE, false, false)); OUR_CORE_LIVE_PROPS.put(DAVElement.LOCK_DISCOVERY, new LivePropertySpecification(DAVElement.LOCK_DISCOVERY, false, false)); OUR_CORE_LIVE_PROPS.put(DAVElement.SUPPORTED_LOCK, new LivePropertySpecification(DAVElement.SUPPORTED_LOCK, false, false)); }; protected ServletDAVHandler(DAVRepositoryManager connector, HttpServletRequest request, HttpServletResponse response) { myRepositoryManager = connector; myRequest = request; myResponse = response; init(); } protected DAVRepositoryManager getRepositoryManager() { return myRepositoryManager; } protected DAVConfig getConfig() { return myRepositoryManager.getDAVConfig(); } public abstract void execute() throws SVNException; protected abstract DAVRequest getDAVRequest(); protected void startElement(DAVElement parent, DAVElement element, Attributes attrs) throws SVNException { getDAVRequest().startElement(parent, element, attrs); } protected void endElement(DAVElement parent, DAVElement element, StringBuffer cdata) throws SVNException { getDAVRequest().endElement(parent, element, cdata); } protected DAVResource getRequestedDAVResource(boolean labelAllowed, boolean useCheckedIn) throws SVNException { return getRequestedDAVResource(labelAllowed, useCheckedIn, null); } protected DAVResource getRequestedDAVResource(boolean labelAllowed, boolean useCheckedIn, String pathInfo) throws SVNException { String label = labelAllowed ? getRequestHeader(LABEL_HEADER) : null; String versionName = getRequestHeader(SVN_VERSION_NAME_HEADER); long version = DAVResource.INVALID_REVISION; try { version = Long.parseLong(versionName); } catch (NumberFormatException e) { } String clientOptions = getRequestHeader(SVN_OPTIONS_HEADER); String baseChecksum = getRequestHeader(SVN_BASE_FULLTEXT_MD5_HEADER); String resultChecksum = getRequestHeader(SVN_RESULT_FULLTEXT_MD5_HEADER); String deltaBase = getRequestHeader(SVN_DELTA_BASE_HEADER); String userAgent = getRequestHeader(USER_AGENT_HEADER); Map clientCapabilities = new HashMap(); clientCapabilities.put(SVNCapability.MERGE_INFO, CAPABILITY_NO); boolean isSVNClient = false; if (userAgent != null && (userAgent.startsWith("SVN/") || userAgent.startsWith("SVNKit"))) { isSVNClient = true; String clientCapabilitiesList = getRequestHeader(HTTPHeader.DAV_HEADER); if (clientCapabilitiesList != null) { for(StringTokenizer tokens = new StringTokenizer(clientCapabilitiesList, ","); tokens.hasMoreTokens();) { String token = tokens.nextToken().trim(); if (DAVElement.MERGE_INFO_OPTION.equalsIgnoreCase(token)) { clientCapabilities.put(SVNCapability.MERGE_INFO, CAPABILITY_YES); } } } } List lockTokens = getLockTokensList(); DAVResource resource = getRepositoryManager().getRequestedDAVResource(isSVNClient, deltaBase, pathInfo, version, clientOptions, baseChecksum, resultChecksum, label, useCheckedIn, lockTokens, clientCapabilities); setDefaultResponseHeaders(); setResponseContentType(DEFAULT_XML_CONTENT_TYPE); setResponseStatus(HttpServletResponse.SC_OK); return resource; } protected List getLockTokensList() throws DAVException { List ifHeaders = DAVServletUtil.processIfHeader(getRequestHeader(HTTPHeader.IF_HEADER)); LinkedList lockTokens = null; if (ifHeaders != null) { for (Iterator ifHeadersIter = ifHeaders.iterator(); ifHeadersIter.hasNext();) { DAVIFHeader ifHeader = (DAVIFHeader) ifHeadersIter.next(); List ifStateList = ifHeader.getStateList(); if (ifStateList != null) { for (Iterator ifStateIter = ifStateList.iterator(); ifStateIter.hasNext();) { DAVIFState ifState = (DAVIFState) ifStateIter.next(); if (ifState.getCondition() == DAVIFState.IF_CONDITION_NORMAL && ifState.getType() == DAVIFStateType.IF_OPAQUE_LOCK) { if (lockTokens == null) { lockTokens = new LinkedList(); } lockTokens.add(ifState.getLockToken()); } } } } } return lockTokens; } protected DAVResourceState getResourceState(DAVResource resource) throws SVNException { if (resource.exists()) { return DAVResourceState.EXISTS; } DAVLockInfoProvider lockInfoProvider = DAVLockInfoProvider.createLockInfoProvider(this, true); try { if (lockInfoProvider.hasLocks(resource)) { return DAVResourceState.LOCK_NULL; } } catch (DAVException e) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.FSFS, "Failed to query lock-null status for " + resource.getResourceURI().getPath()); return DAVResourceState.ERROR; } return DAVResourceState.NULL; } protected LivePropertySpecification findLiveProperty(DAVElement property) { String nameSpace = property.getNamespace(); if (!DAVElement.DAV_NAMESPACE.equals(nameSpace) && !DAVElement.SVN_DAV_PROPERTY_NAMESPACE.equals(nameSpace)) { return null; } LivePropertySpecification lps = (LivePropertySpecification) OUR_LIVE_PROPS.get(property); if (lps == null) { //search in core props lps = (LivePropertySpecification) OUR_CORE_LIVE_PROPS.get(property); } return lps; } protected void validateRequest(DAVResource resource, DAVDepth depth, int flags, DAVLockScope lockScope, String lockToken, DAVLockInfoProvider lockInfoProvider) throws SVNException { boolean setETag = false; String eTag = getRequestHeader(ETAG_HEADER); if (eTag == null) { eTag = resource.getETag(); if (eTag != null && eTag.length() > 0) { setResponseHeader(ETAG_HEADER, eTag); setETag = true; } } DAVResourceState resourceState = getResourceState(resource); int result = meetsCondition(resource, resourceState); if (setETag) { setResponseHeader(ETAG_HEADER, null); } if (result != 0) { throw new DAVException(null, null, result, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } LinkedList ifHeaders = DAVServletUtil.processIfHeader(getRequestHeader(HTTPHeader.IF_HEADER)); if (lockToken != null) { DAVIFState ifState = new DAVIFState(DAVIFState.IF_CONDITION_NORMAL, null, lockToken, DAVIFStateType.IF_OPAQUE_LOCK); DAVIFHeader ifHeader = new DAVIFHeader(resource.getResourceURI().getRequestURI(), true); ifHeader.addIFState(ifState); if (ifHeaders == null) { ifHeaders = new LinkedList(); } ifHeaders.addFirst(ifHeader); } if (lockInfoProvider == null) { lockInfoProvider = DAVLockInfoProvider.createLockInfoProvider(this, false); } DAVException exception = null; DAVResponse response = null; DAVValidateWalker validateHandler = new DAVValidateWalker(); if (resource.exists() && depth.getID() > 0) { DAVResourceWalker walker = new DAVResourceWalker(); int walkType = DAVResourceWalker.DAV_WALKTYPE_NORMAL | DAVResourceWalker.DAV_WALKTYPE_LOCKNULL; try { response = walker.walk(lockInfoProvider, resource, ifHeaders, flags, lockScope, walkType, validateHandler, DAVDepth.DEPTH_INFINITY); } catch (DAVException dave) { exception = dave; } } else { try { validateHandler.validateResourceState(ifHeaders, resource, lockInfoProvider, lockScope, flags); } catch (DAVException dave) { exception = dave; } } if (exception == null && (flags & DAV_VALIDATE_PARENT) != 0) { DAVResource parentResource = null; try { parentResource = DAVResourceHelper.createParentResource(resource); } catch (DAVException dave) { exception = dave; } if (exception == null) { try { validateHandler.validateResourceState(ifHeaders, parentResource, lockInfoProvider, lockScope, flags | DAV_VALIDATE_IS_PARENT); } catch (DAVException dave) { exception = dave; } if (exception != null) { String description = "A validation error has occurred on the parent resource, preventing the operation on the resource specified by the Request-URI."; if (exception.getMessage() != null) { description += " The error was: " + exception.getMessage(); } response = new DAVResponse(description, parentResource.getResourceURI().getRequestURI(), response, null, exception.getResponseCode()); exception = null; } } } if (exception == null && response != null) { if ((flags & DAV_VALIDATE_USE_424) != 0) { throw new DAVException("An error occurred on another resource, preventing the requested operation on this resource.", SC_FAILED_DEPENDANCY, 0, response); } DAVPropsResult propStat = null; if ((flags & DAV_VALIDATE_ADD_LD) != 0) { propStat = new DAVPropsResult(); propStat.addPropStatsText("\n\nHTTP/1.1 424 Failed Dependency\n\n"); } response = new DAVResponse("An error occurred on another resource, preventing the requested operation on this resource.", resource.getResourceURI().getRequestURI(), response, propStat, SC_FAILED_DEPENDANCY); throw new DAVException("Error(s) occurred on resources during the validation process.", SC_MULTISTATUS, 0, response); } if (exception != null) { exception.setResponse(response); throw exception; } } protected SVNDeltaReader openStream(DAVResource resource, int mode) throws DAVException { if (mode == DAV_MODE_WRITE_TRUNC || mode == DAV_MODE_WRITE_SEEKABLE) { if (resource.getType() != DAVResourceType.WORKING) { throw new DAVException("Resource body changes may only be made to working resources [at this time].", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } } if (mode == DAV_MODE_WRITE_SEEKABLE) { throw new DAVException("Resource body writes cannot use ranges [at this time].", HttpServletResponse.SC_NOT_IMPLEMENTED, 0); } String path = resource.getResourceURI().getPath(); FSRoot root = resource.getRoot(); FSFS fsfs = resource.getFSFS(); FSTransactionInfo txn = resource.getTxnInfo(); FSCommitter committer = getCommitter(fsfs, root, txn, resource.getLockTokens(), resource.getUserName()); SVNNodeKind kind = DAVServletUtil.checkPath(resource.getRoot(), resource.getResourceURI().getPath()); if (kind == SVNNodeKind.NONE) { try { committer.makeFile(path); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create file within the repository.", null); } } if (resource.isAutoCheckedOut() && myRequest.getContentType() != null) { SVNProperties props = null; try { props = fsfs.getProperties(root.getRevisionNode(path)); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error fetching mime-type property.", null); } String mimeType = props.getStringValue(SVNProperty.MIME_TYPE); if (mimeType == null) { try { committer.changeNodeProperty(path, SVNProperty.MIME_TYPE, SVNPropertyValue.create(myRequest.getContentType())); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not set mime-type property.", null); } } } ISVNDeltaConsumer deltaConsumer = getDeltaConsumer(root, committer, fsfs, resource.getUserName(), resource.getLockTokens()); try { deltaConsumer.applyTextDelta(path, resource.getBaseChecksum()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not prepare to write the file", null); } if (isSVNDiff()) { return new SVNDeltaReader(); } return null; } protected void moveResource(DAVResource srcResource, DAVResource dstResource) throws DAVException { if (srcResource.getType() != DAVResourceType.REGULAR || dstResource.getType() != DAVResourceType.REGULAR || !getConfig().isAutoVersioning()) { throw new DAVException("MOVE only allowed on two public URIs, and autoversioning must be active.", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } checkOut(dstResource, true, false, false, null); FSCommitter committer = getCommitter(dstResource.getFSFS(), dstResource.getRoot(), dstResource.getTxnInfo(), dstResource.getLockTokens(), dstResource.getUserName()); String srcPath = srcResource.getResourceURI().getPath(); String dstPath = dstResource.getResourceURI().getPath(); try { committer.makeCopy((FSRevisionRoot) srcResource.getRoot(), srcPath, dstPath, true); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to make a filesystem copy.", null); } try { committer.deleteNode(srcPath); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not delete the src resource.", null); } checkIn(dstResource, false, false); } protected void copyResource(DAVResource srcResource, DAVResource dstResource) throws DAVException { if (dstResource.isBaseLined() && dstResource.getType() == DAVResourceType.VERSION) { throw new DAVException("Illegal: COPY Destination is a baseline.", HttpServletResponse.SC_PRECONDITION_FAILED, 0); } if (dstResource.getType() == DAVResourceType.REGULAR && !getConfig().isAutoVersioning()) { throw new DAVException("COPY called on regular resource, but autoversioning is not active.", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } if (dstResource.getType() == DAVResourceType.REGULAR) { checkOut(dstResource, true, false, false, null); } FSFS srcFSFS = srcResource.getFSFS(); FSFS dstFSFS = dstResource.getFSFS(); if (!srcFSFS.getDBRoot().equals(dstFSFS.getDBRoot())) { throw new DAVException("Copy source and destination are in different repositories.", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, 0, null); } FSCommitter committer = getCommitter(dstResource.getFSFS(), dstResource.getRoot(), dstResource.getTxnInfo(), dstResource.getLockTokens(), dstResource.getUserName()); String srcPath = srcResource.getResourceURI().getPath(); String dstPath = dstResource.getResourceURI().getPath(); try { committer.makeCopy((FSRevisionRoot) srcResource.getRoot(), srcPath, dstPath, true); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to make a filesystem copy.", null); } if (dstResource.isAutoCheckedOut()) { checkIn(dstResource, false, false); } } protected int unlock(DAVResource resource, String lockToken) { DAVLockInfoProvider lockProvider = null; try { lockProvider = DAVLockInfoProvider.createLockInfoProvider(this, false); } catch (SVNException svne) { return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } DAVResource lockResource = resource; if (lockToken != null) { try { lockResource = DAVResourceHelper.getDirectResource(lockProvider, lockToken, resource); } catch (DAVException dave) { return dave.getResponseCode(); } } int walkType = DAVResourceWalker.DAV_WALKTYPE_NORMAL | DAVResourceWalker.DAV_WALKTYPE_LOCKNULL; DAVResourceWalker walker = new DAVResourceWalker(); DAVUnlockWalker unlockHandler = new DAVUnlockWalker(lockToken, this); try { walker.walk(lockProvider, lockResource, null, 0, null, walkType, unlockHandler, DAVDepth.DEPTH_INFINITY); } catch (DAVException dave) { return dave.getResponseCode(); } return HttpServletResponse.SC_OK; } protected DAVResource checkOut(DAVResource resource, boolean isAutoCheckOut, boolean isUnreserved, boolean isCreateActivity, List activities) throws DAVException { DAVResourceType resourceType = resource.getResourceURI().getType(); FSFS fsfs = resource.getFSFS(); if (isAutoCheckOut) { if (resourceType == DAVResourceType.VERSION && resource.isBaseLined()) { return null; } if (resourceType != DAVResourceType.REGULAR) { throw new DAVException("auto-checkout attempted on non-regular version-controlled resource.", null, HttpServletResponse.SC_METHOD_NOT_ALLOWED, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } if (resource.isBaseLined()) { new DAVException("auto-checkout attempted on baseline collection, which is not supported.", null, HttpServletResponse.SC_METHOD_NOT_ALLOWED, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } String sharedActivity = DAVServlet.getSharedActivity(); String sharedTxnName = null; FSTransactionInfo sharedTxnInfo = null; if (sharedActivity == null) { try { sharedActivity = SVNUUIDGenerator.formatUUID(SVNUUIDGenerator.generateUUID()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot generate UUID for a shared activity", null); } sharedTxnInfo = DAVServletUtil.createActivity(resource, fsfs); sharedTxnName = sharedTxnInfo.getTxnId(); DAVServletUtil.storeActivity(resource, sharedTxnInfo.getTxnId()); DAVServlet.setSharedActivity(sharedActivity); } if (sharedTxnName == null) { sharedTxnName = DAVServletUtil.getTxn(resource.getActivitiesDB(), sharedActivity); if (sharedTxnName == null) { throw new DAVException("Cannot look up a txn_name by activity", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, null, null, null, 0, null); } } resource = DAVWorkingResourceHelper.createWorkingResource(resource, sharedActivity, sharedTxnName, true); resource.setIsAutoCkeckedOut(true); FSTransactionInfo txnInfo = DAVServletUtil.openTxn(fsfs, resource.getTxnName()); FSTransactionRoot txnRoot = null; try { txnRoot = fsfs.createTransactionRoot(txnInfo); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open a (transaction) root in the repository", null); } resource.setTxnInfo(txnInfo); resource.setRoot(txnRoot); return null; } if (resourceType != DAVResourceType.VERSION) { throw new DAVException("CHECKOUT can only be performed on a version resource [at this time].", null, HttpServletResponse.SC_METHOD_NOT_ALLOWED, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } if (isCreateActivity) { throw new DAVException("CHECKOUT can not create an activity at this time. Use MKACTIVITY first.", null, HttpServletResponse.SC_NOT_IMPLEMENTED, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } if (isUnreserved) { throw new DAVException("Unreserved checkouts are not yet available. A version history may not be checked out more than once, into a specific activity.", null, HttpServletResponse.SC_NOT_IMPLEMENTED, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } if (activities == null) { throw new DAVException("An activity must be provided for checkout.", null, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.INCOMPLETE_DATA.getCode(), null); } if (activities.size() != 1) { throw new DAVException("Only one activity may be specified within the CHECKOUT.", null, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.INCORRECT_PARAMS.getCode(), null); } DAVURIInfo parse = null; try { parse = DAVPathUtil.simpleParseURI((String) activities.get(0), resource); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_CONFLICT, "The activity href could not be parsed properly.", null); } if (parse.getActivityID() == null) { throw new DAVException("The provided href is not an activity URI.", null, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.INCORRECT_PARAMS.getCode(), null); } String txnName = DAVServletUtil.getTxn(resource.getActivitiesDB(), parse.getActivityID()); if (txnName == null) { throw new DAVException("The specified activity does not exist.", null, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.APMOD_ACTIVITY_NOT_FOUND.getCode(), null); } if (resource.isBaseLined() || !SVNRevision.isValidRevisionNumber(resource.getRevision())) { long youngestRevision = -1; try { youngestRevision = fsfs.getYoungestRevision(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not determine the youngest revision for verification against the baseline being checked out.", null); } if (resource.getRevision() != youngestRevision) { throw new DAVException("The specified baseline is not the latest baseline, so it may not be checked out.", null, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.APMOD_BAD_BASELINE.getCode(), null); } } else { FSTransactionInfo txnInfo = DAVServletUtil.openTxn(fsfs, txnName); FSTransactionRoot txnRoot = null; String reposPath = resource.getResourceURI().getPath(); try { txnRoot = fsfs.createTransactionRoot(txnInfo); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not open the transaction tree.", null); } long txnCreatedRevision = -1; try { FSRevisionNode node = txnRoot.getRevisionNode(reposPath); txnCreatedRevision = node.getCreatedRevision(); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not get created-rev of transaction node.", null); } if (SVNRevision.isValidRevisionNumber(txnCreatedRevision)) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "resource.getRevision(): " + resource.getRevision() + ", txnCreatedRevision: " + txnCreatedRevision); SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "resource type: " + resource.getType()); if (resource.getRevision() < txnCreatedRevision) { throw new DAVException("resource out of date; try updating", null, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.FS_CONFLICT.getCode(), null); } else if (resource.getRevision() > txnCreatedRevision) { String txnNodeRevID = null; try { FSRevisionNode node = txnRoot.getRevisionNode(reposPath); txnNodeRevID = node.getId().getNodeID(); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage(); throw new DAVException("Unable to fetch the node revision id of the version resource within the transaction.", null, HttpServletResponse.SC_CONFLICT, err, SVNLogType.FSFS, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, err.getErrorCode().getCode(), null); } String urlNodeRevID = null; try { FSRoot root = resource.getRoot(); FSRevisionNode node = root.getRevisionNode(reposPath); urlNodeRevID = node.getId().getNodeID(); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage(); throw new DAVException("Unable to fetch the node revision id of the version resource within the revision.", null, HttpServletResponse.SC_CONFLICT, err, SVNLogType.FSFS, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, err.getErrorCode().getCode(), null); } if (!urlNodeRevID.equals(txnNodeRevID)) { throw new DAVException("version resource newer than txn (restart the commit)", null, HttpServletResponse.SC_CONFLICT, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.FS_CONFLICT.getCode(), null); } } } } return DAVWorkingResourceHelper.createWorkingResource(resource, parse.getActivityID(), txnName, false); } protected DAVResource checkIn(DAVResource resource, boolean keepCheckedOut, boolean createVersionResource) throws DAVException { if (resource.getType() != DAVResourceType.WORKING) { throw new DAVException("CHECKIN called on non-working resource.", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } DAVResource versionResource = null; DAVResourceURI resourceURI = resource.getResourceURI(); String sharedActivity = DAVServlet.getSharedActivity(); if (sharedActivity != null && sharedActivity.equals(resource.getActivityID())) { String sharedTxnName = DAVServletUtil.getTxn(resource.getActivitiesDB(), sharedActivity); if (sharedTxnName == null) { throw new DAVException("Cannot look up a txn_name by activity", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } if (resource.getTxnName() != null && !sharedTxnName.equals(resource.getTxnName())) { throw new DAVException("Internal txn_name doesn't match autoversioning transaction.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } if (resource.getTxnInfo() == null) { throw new DAVException("Autoversioning txn isn't open when it should be.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); } DAVServletUtil.setAutoRevisionProperties(resource); FSCommitter committer = getCommitter(resource.getFSFS(), resource.getRoot(), resource.getTxnInfo(), resource.getLockTokens(), resource.getUserName()); StringBuffer conflictPath = new StringBuffer(); long newRev = SVNRepository.INVALID_REVISION; try { newRev = committer.commitTxn(true, true, null, conflictPath); } catch (SVNException svne) { try { FSCommitter.abortTransaction(resource.getFSFS(), resource.getTxnInfo().getTxnId()); } catch (SVNException svne2) { //ignore } String message = null; Object[] objects = null; if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.FS_CONFLICT) { message = "A conflict occurred during the CHECKIN processing. The problem occurred with the \"{0}\" resource."; objects = new Object[] { conflictPath.toString() }; } else { message = "An error occurred while committing the transaction."; } DAVServletUtil.deleteActivity(resource, sharedActivity); DAVServlet.setSharedActivity(null); throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_CONFLICT, message, objects); } DAVServletUtil.deleteActivity(resource, sharedActivity); if (createVersionResource) { String uri = DAVPathUtil.buildURI(resourceURI.getContext(), DAVResourceKind.VERSION, newRev, resourceURI.getPath(), false); versionResource = DAVVersionResourceHelper.createVersionResource(resource, uri); } } resource.setTxnName(null); resource.setTxnInfo(null); if (!keepCheckedOut) { resource.setIsAutoCkeckedOut(false); DAVResourceHelper.convertWorkingToRegular(resource); } return versionResource; } protected void uncheckOut(DAVResource resource) throws DAVException { if (resource.getType() != DAVResourceType.WORKING) { throw new DAVException("UNCHECKOUT called on non-working resource.", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, null, DAVXMLUtil.SVN_DAV_ERROR_TAG, DAVElement.SVN_DAV_ERROR_NAMESPACE, SVNErrorCode.UNSUPPORTED_FEATURE.getCode(), null); } FSTransactionInfo txnInfo = resource.getTxnInfo(); if (txnInfo != null) { try { FSCommitter.abortTransaction(resource.getFSFS(), txnInfo.getTxnId()); } catch (SVNException svne) { //ignore } } DAVResourceURI resourceURI = resource.getResourceURI(); if (resourceURI.getActivityID() != null) { try { DAVServletUtil.deleteActivity(resource, resourceURI.getActivityID()); } catch (DAVException dave) { //ignore } DAVServlet.setSharedActivity(null); } resource.setTxnName(null); resource.setTxnInfo(null); resource.setIsAutoCkeckedOut(false); DAVResourceHelper.convertWorkingToRegular(resource); } protected DAVAutoVersionInfo autoCheckOut(DAVResource resource, boolean isParentOnly) throws DAVException { DAVAutoVersionInfo info = new DAVAutoVersionInfo(); DAVLockInfoProvider[] lockProvider = new DAVLockInfoProvider[0]; if (!resource.exists() || isParentOnly) { DAVResource parentResource = null; try { parentResource = DAVResourceHelper.createParentResource(resource); } catch (DAVException dave) { autoCheckIn(resource, true, false, info); throw dave; } if (parentResource == null || !parentResource.exists()) { autoCheckIn(resource, true, false, info); throw new DAVException("Missing one or more intermediate collections. Cannot create resource {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI()) }, HttpServletResponse.SC_CONFLICT, 0); } info.setParentResource(parentResource); if (parentResource.isVersioned() && !parentResource.isWorking()) { boolean checkOutParent = false; try { checkOutParent = canAutoCheckOut(parentResource, lockProvider, parentResource.getAutoVersion()); } catch (DAVException dave) { autoCheckIn(resource, true, false, info); throw dave; } if (!checkOutParent) { autoCheckIn(resource, true, false, info); throw new DAVException("", HttpServletResponse.SC_CONFLICT, 0); } try { checkOut(parentResource, true, false, false, null); } catch (DAVException dave) { autoCheckIn(resource, true, false, info); throw new DAVException("Unable to auto-checkout parent collection. Cannot create resource {0}.", new Object[] { resource.getResourceURI().getRequestURI() }, HttpServletResponse.SC_CONFLICT, dave, 0); } info.setParentCheckedOut(true); } } if (isParentOnly) { return info; } if (!resource.exists() && resource.getAutoVersion() == DAVAutoVersion.ALWAYS) { try { resource.versionControl(null); } catch (DAVException dave) { autoCheckIn(resource, true, false, info); throw new DAVException("Unable to create versioned resource {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI()) }, HttpServletResponse.SC_CONFLICT, dave, 0); } info.setResourceVersioned(true); } if (resource.isVersioned() && !resource.isWorking()) { boolean checkOutResource = false; try { checkOutResource = canAutoCheckOut(resource, lockProvider, resource.getAutoVersion()); } catch (DAVException dave) { autoCheckIn(resource, true, false, info); throw dave; } if (!checkOutResource) { autoCheckIn(resource, true, false, info); throw new DAVException("", HttpServletResponse.SC_CONFLICT, 0); } try { checkOut(resource, true, false, false, null); } catch (DAVException dave) { autoCheckIn(resource, true, false, info); throw new DAVException("Unable to checkout resource {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI()) }, HttpServletResponse.SC_CONFLICT, 0); } info.setResourceCheckedOut(true); } return info; } protected boolean canAutoCheckOut(DAVResource resource, DAVLockInfoProvider[] lockProvider, DAVAutoVersion autoVersion) throws DAVException { boolean autoCheckOut = false; DAVLock lock = null; if (autoVersion == DAVAutoVersion.ALWAYS) { autoCheckOut = true; } else if (autoVersion == DAVAutoVersion.LOCKED) { if (lockProvider[0] == null) { try { lockProvider[0] = DAVLockInfoProvider.createLockInfoProvider(this, false); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot open lock database to determine auto-versioning behavior.", null); } } try { lock = lockProvider[0].getLock(resource); } catch (DAVException dave) { throw new DAVException("The locks could not be queried for determining auto-versioning behavior.", null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, dave, 0); } if (lock != null) { autoCheckOut = true; } } return autoCheckOut; } protected void autoCheckIn(DAVResource resource, boolean undo, boolean unlock, DAVAutoVersionInfo info) throws DAVException { if (undo) { if (resource != null) { if (info.isResourceCheckedOut()) { try { uncheckOut(resource); } catch (DAVException dave) { throw new DAVException("Unable to undo auto-checkout of resource {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI()) }, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } } if (info.isResourceVersioned()) { try { removeResource(resource); } catch (DAVException dave) { throw new DAVException("Unable to undo auto-version-control of resource {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI()) }, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } } } if (info.getParentResource() != null && info.isParentCheckedOut()) { try { uncheckOut(info.getParentResource()); } catch (DAVException dave) { throw new DAVException("Unable to undo auto-checkout of parent collection {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(info.getParentResource().getResourceURI().getRequestURI()) }, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } } return; } if (resource != null && resource.isWorking() && (unlock || info.isResourceCheckedOut())) { DAVAutoVersion autoVersion = resource.getAutoVersion(); if (autoVersion == DAVAutoVersion.ALWAYS || (unlock && autoVersion == DAVAutoVersion.LOCKED)) { try { checkIn(resource, false, false); } catch (DAVException dave) { throw new DAVException("Unable to auto-checkin resource {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(resource.getResourceURI().getRequestURI()) }, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } } } if (!unlock && info.isParentCheckedOut() && info.getParentResource() != null && info.getParentResource().getType() == DAVResourceType.WORKING) { DAVAutoVersion autoVersion = info.getParentResource().getAutoVersion(); if (autoVersion == DAVAutoVersion.ALWAYS) { try { checkIn(info.getParentResource(), false, false); } catch (DAVException dave) { throw new DAVException("Unable to auto-checkin parent collection {0}.", new Object[] { SVNEncodingUtil.xmlEncodeCDATA(info.getParentResource().getResourceURI().getRequestURI()) }, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, SVNLogType.NETWORK, Level.FINE, dave, null, null, 0, null); } } } } protected void removeResource(DAVResource resource) throws DAVException { DAVResourceURI uri = resource.getResourceURI(); DAVResourceType resourceType = uri.getType(); if (resourceType != DAVResourceType.REGULAR && resourceType != DAVResourceType.WORKING && resourceType != DAVResourceType.ACTIVITY) { throw new DAVException("DELETE called on invalid resource type.", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } DAVConfig config = getConfig(); if (resourceType == DAVResourceType.REGULAR && !config.isAutoVersioning()) { throw new DAVException("DELETE called on regular resource, but autoversioning is not active.", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } if (resourceType == DAVResourceType.ACTIVITY) { DAVServletUtil.deleteActivity(resource, uri.getActivityID()); return; } if (resourceType == DAVResourceType.REGULAR) { checkOut(resource, true, false, false, null); } if (SVNRevision.isValidRevisionNumber(resource.getVersion())) { long createdRevision = SVNRepository.INVALID_REVISION; try { createdRevision = resource.getCreatedRevisionUsingFS(null); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not get created rev of resource", null); } if (resource.getVersion() < createdRevision) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_OUT_OF_DATE, "Item ''{0}'' is out of date", uri.getPath()); throw DAVException.convertError(err, HttpServletResponse.SC_CONFLICT, "Can''t DELETE out-of-date resource", null); } } //MERGE requests send can provide locks in a request body, //COPY, MOVE requests do not, so check for the valid xml exists if (getDAVRequest() != null) { Map locks = parseLocks(getDAVRequest().getRootElement(), uri.getPath()); if (!locks.isEmpty()) { resource.setLockTokens(locks.values()); } } FSCommitter committer = getCommitter(resource.getFSFS(), resource.getRoot(), resource.getTxnInfo(), resource.getLockTokens(), resource.getUserName()); try { committer.deleteNode(uri.getPath()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not delete the resource", null); } if (resource.isAutoCheckedOut()) { checkIn(resource, false, false); } } protected Map parseLocks(DAVElementProperty rootElement, String pathPrefix) throws DAVException { Map pathsToLockTokens = new HashMap(); List namespaces = getNamespaces(); if (namespaces == null || !namespaces.contains(DAVElement.SVN_NAMESPACE)) { return pathsToLockTokens; } DAVElement rootElementName = rootElement.getName(); DAVElementProperty child = null; if (rootElementName == DAVElement.SVN_LOCK_TOKEN_LIST) { child = rootElement; } else { List children = rootElement.getChildren(); if (children != null) { for (Iterator childIter = children.iterator(); childIter.hasNext();) { DAVElementProperty nextChild = (DAVElementProperty) childIter.next(); if (nextChild.getName() == DAVElement.SVN_LOCK_TOKEN_LIST) { child = nextChild; break; } } } } if (child == null) { return pathsToLockTokens; } List children = child.getChildren(); if (children != null) { for (Iterator childIter = children.iterator(); childIter.hasNext();) { DAVElementProperty lockChild = (DAVElementProperty) childIter.next(); if (lockChild.getName() != DAVElement.SVN_LOCK) { continue; } String lockPath = null; String lockToken = null; List lockChildren = lockChild.getChildren(); for (Iterator lockChildrenIter = lockChildren.iterator(); lockChildrenIter.hasNext();) { DAVElementProperty lockElementChild = (DAVElementProperty) lockChildrenIter.next(); if (lockElementChild.getName() == LOCK_PATH_ELEM) { String cdata = lockElementChild.getFirstValue(false); DAVPathUtil.testCanonical(cdata); lockPath = SVNPathUtil.append(pathPrefix, cdata); if (!lockPath.startsWith("/")) { lockPath = "/" + lockPath; } if (lockPath != null && lockToken != null) { pathsToLockTokens.put(lockPath, lockToken); lockPath = null; lockToken = null; } } else if (lockElementChild.getName() == LOCK_TOKEN_ELEM) { lockToken = lockElementChild.getFirstValue(true); if (lockPath != null && lockToken != null) { pathsToLockTokens.put(lockPath, lockToken); lockPath = null; lockToken = null; } } } } } return pathsToLockTokens; } protected DAVDepth getRequestDepth(DAVDepth defaultDepth) throws SVNException { String depth = getRequestHeader(DEPTH_HEADER); if (depth == null) { return defaultDepth; } DAVDepth result = DAVDepth.parseDepth(depth); if (result == null) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, "Invalid depth ''{0}''", depth), SVNLogType.NETWORK); } return result; } protected Date getTimeout() { String timeoutHeader = getRequestHeader(HTTPHeader.TIMEOUT_HEADER); if (timeoutHeader == null) { return null; } timeoutHeader = timeoutHeader.trim(); String[] values = timeoutHeader.split("[\\t\\s]"); for (int i = 0; i < values.length; i++) { String value = values[i]; if ("Infinite".equalsIgnoreCase(value)) { return null; } if (value.startsWith("Second-")) { value = value.substring(7); long expirationValue = 0; try { expirationValue = Long.parseLong(value); } catch (NumberFormatException nfe) { } return new Date(System.currentTimeMillis() + expirationValue); } } return null; } protected void setDefaultResponseHeaders() { if (getRequestHeader(LABEL_HEADER) != null && getRequestHeader(LABEL_HEADER).length() > 0) { setResponseHeader(VARY_HEADER, LABEL_HEADER); } } protected String getURI() { return myRequest.getRequestURI(); } protected String getRequestHeader(String name) { return myRequest.getHeader(name); } protected String getRequestMethod() { return myRequest.getMethod(); } protected Enumeration getRequestHeaders(String name) { return myRequest.getHeaders(name); } protected long getRequestDateHeader(String name) { return myRequest.getDateHeader(name); } protected boolean isSVNDiff() { String contentType = myRequest.getContentType(); return contentType != null && contentType.equals(HTTPHeader.SVNDIFF_MIME_TYPE); } protected long[] parseRange() { String range = getRequestHeader(HTTPHeader.CONTENT_RANGE_HEADER); if (range == null) { return null; } range = range.toLowerCase(); if (!range.startsWith("bytes ") || range.indexOf("-") < 0 || range.indexOf("/") < 0) { return null; } range = range.substring("bytes ".length()).trim(); int ind = range.indexOf('-'); String rangeStartSubstring = range.substring(0, ind); long rangeStart = -1; try { rangeStart = Long.parseLong(rangeStartSubstring); } catch (NumberFormatException nfe) { return null; } if (rangeStart < 0) { return null; } range = range.substring(ind + 1); ind = range.indexOf('/'); String rangeEndSubstring = range.substring(0, ind); long rangeEnd = -1; try { rangeEnd = Long.parseLong(rangeEndSubstring); } catch (NumberFormatException nfe) { return null; } if (rangeEnd < 0 || rangeEnd < rangeStart) { return null; } if (range.charAt(ind + 1) != '*') { range = range.substring(ind + 1); long length = -1; try { length = Long.parseLong(range); } catch (NumberFormatException nfe) { return null; } if (length <= rangeEnd) { return null; } } return new long[] { rangeStart, rangeEnd }; } protected InputStream getRequestInputStream() throws SVNException { try { return myRequest.getInputStream(); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e), e, SVNLogType.NETWORK); } return null; } protected HttpServletRequest getRequest() { return myRequest; } protected void setResponseHeader(String name, String value) { myResponse.setHeader(name, value); } protected void addResponseHeader(String name, String value) { myResponse.addHeader(name, value); } protected void setResponseStatus(int statusCode) { myResponse.setStatus(statusCode); } protected void sendError(int errorCode, String message) { try { myResponse.sendError(errorCode, message); } catch (IOException e) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, message); } } protected void setResponseContentType(String contentType) { myResponse.setContentType(contentType); } protected void setResponseContentLength(int length) { myResponse.setContentLength(length); } protected Writer getResponseWriter() throws SVNException { try { return myResponse.getWriter(); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e), e, SVNLogType.NETWORK); } return null; } protected void createdCollection(DAVResource resource) throws DAVException { if (resource.getType() != DAVResourceType.WORKING && resource.getType() != DAVResourceType.REGULAR) { throw new DAVException("Collections can only be created within a working or regular collection [at this time].", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } if (resource.getType() == DAVResourceType.REGULAR && !getConfig().isAutoVersioning()) { throw new DAVException("MKCOL called on regular resource, but autoversioning is not active.", HttpServletResponse.SC_METHOD_NOT_ALLOWED, 0); } if (resource.getType() == DAVResourceType.REGULAR) { checkOut(resource, true, false, false, null); } FSCommitter committer = getCommitter(resource.getFSFS(), resource.getRoot(), resource.getTxnInfo(), resource.getLockTokens(), resource.getUserName()); try { committer.makeDir(resource.getResourceURI().getPath()); } catch (SVNException svne) { throw DAVException.convertError(svne.getErrorMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create the collection.", null); } if (resource.isAutoCheckedOut()) { checkIn(resource, false, false); } } protected OutputStream getResponseOutputStream() throws SVNException { try { return myResponse.getOutputStream(); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e), e, SVNLogType.NETWORK); } return null; } protected void handleDAVCreated(String location, String what, boolean isReplaced) throws SVNException { if (location == null) { location = getURI(); } if (isReplaced) { setResponseStatus(HttpServletResponse.SC_NO_CONTENT); return; } setResponseHeader(HTTPHeader.LOCATION_HEADER, constructURL(location)); String body = what + " " + SVNEncodingUtil.xmlEncodeCDATA(location) + " has been created."; response(body, DAVServlet.getStatusLine(HttpServletResponse.SC_CREATED), HttpServletResponse.SC_CREATED); } protected void notifyCreated(DAVResource resource, DAVLockInfoProvider lockProvider, DAVResourceState resourceState, DAVDepth depth) throws DAVException { if (resourceState == DAVResourceState.LOCK_NULL) { if (depth != DAVDepth.DEPTH_ZERO) { lockProvider.inheritLocks(resource, false); } } else if (resourceState == DAVResourceState.NULL) { try { lockProvider.inheritLocks(resource, true); } catch (DAVException dave) { throw new DAVException("The resource was created successfully, but there was a problem inheriting locks from the parent resource.", dave.getResponseCode(), dave, 0); } } } protected void response(String body, String statusLine, int statusCode) throws SVNException { setResponseStatus(statusCode); setResponseContentType("text/html; charset=ISO-8859-1"); StringBuffer responseBuffer = new StringBuffer(); responseBuffer.append(DAV_RESPONSE_BODY_1); responseBuffer.append(statusLine); responseBuffer.append(DAV_RESPONSE_BODY_2); responseBuffer.append(statusLine.substring(4)); responseBuffer.append(DAV_RESPONSE_BODY_3); responseBuffer.append(body); responseBuffer.append(DAV_RESPONSE_BODY_4); appendServerSignature(responseBuffer, "
\n"); responseBuffer.append(DAV_RESPONSE_BODY_5); String responseBody = responseBuffer.toString(); try { setResponseContentLength(responseBody.getBytes(UTF8_ENCODING).length); } catch (UnsupportedEncodingException e) { setResponseContentLength(responseBody.getBytes().length); } try { getResponseWriter().write(responseBody); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } protected String constructURL(String location) { StringBuffer url = new StringBuffer (); String scheme = myRequest.getScheme(); String host = myRequest.getServerName(); url.append(scheme); url.append("://"); url.append(host); int port = myRequest.getServerPort(); if ((scheme.equals ("http") && port != 80) || (scheme.equals ("https") && port != 443)) { url.append(':'); url.append(port); } if (!location.startsWith("/")) { url.append('/'); } url.append(location); return url.toString(); } protected void appendServerSignature(StringBuffer buffer, String prefix) { buffer.append(prefix); buffer.append("
"); ServletContext context = myRequest.getSession().getServletContext(); buffer.append(context.getServerInfo()); buffer.append(" "); buffer.append(Version.getVersionString()); buffer.append(" "); String host = myRequest.getServerName(); buffer.append("Server at "); buffer.append(SVNEncodingUtil.xmlEncodeCDATA(host)); buffer.append(" Port "); int port = myRequest.getServerPort(); buffer.append(port); buffer.append("
\n"); } protected static Collection getSupportedLiveProperties(DAVResource resource, Collection properties) { if (properties == null) { properties = new ArrayList(); } properties.add(DAVElement.DEADPROP_COUNT); properties.add(DAVElement.REPOSITORY_UUID); properties.add(DAVElement.VERSION_CONTROLLED_CONFIGURATION); if (resource.getResourceURI().getKind() != DAVResourceKind.BASELINE_COLL) { properties.add(DAVElement.BASELINE_COLLECTION); } else { properties.remove(DAVElement.BASELINE_COLLECTION); } properties.add(DAVElement.BASELINE_RELATIVE_PATH); properties.add(DAVElement.RESOURCE_TYPE); properties.add(DAVElement.CHECKED_IN); properties.add(DAVElement.GET_ETAG); properties.add(DAVElement.CREATOR_DISPLAY_NAME); properties.add(DAVElement.CREATION_DATE); properties.add(DAVElement.GET_LAST_MODIFIED); properties.add(DAVElement.VERSION_NAME); properties.add(DAVElement.GET_CONTENT_TYPE); if (!resource.isCollection()) { properties.add(DAVElement.GET_CONTENT_LENGTH); properties.add(DAVElement.MD5_CHECKSUM); } else { properties.remove(DAVElement.GET_CONTENT_LENGTH); properties.remove(DAVElement.MD5_CHECKSUM); } return properties; } protected int checkPreconditions(String eTag, Date lastModified) { lastModified = lastModified == null ? new Date() : lastModified; long lastModifiedTime = lastModified.getTime(); Enumeration ifMatch = getRequestHeaders(IF_MATCH_HEADER); if (ifMatch != null && ifMatch.hasMoreElements()) { String first = (String) ifMatch.nextElement(); if (!first.startsWith("*") && (eTag == null || eTag.startsWith("W") || !first.equals(eTag) || !containsValue(ifMatch, eTag, null))) { return HttpServletResponse.SC_PRECONDITION_FAILED; } } else { long ifUnmodified = getRequestDateHeader(IF_UNMODIFIED_SINCE_HEADER); if (ifUnmodified != -1 && lastModifiedTime > ifUnmodified) { return HttpServletResponse.SC_PRECONDITION_FAILED; } } boolean notModified = false; Enumeration ifNoneMatch = getRequestHeaders(IF_NONE_MATCH_HEADER); if (ifNoneMatch != null && ifNoneMatch.hasMoreElements()) { String first = (String) ifNoneMatch.nextElement(); if (DAVHandlerFactory.METHOD_GET.equals(getRequestMethod())) { if (first.startsWith("*")) { notModified = true; } else if (eTag != null) { if (getRequestHeader(RANGE_HEADER) != null) { notModified = !eTag.startsWith("W") && containsValue(ifNoneMatch, eTag, null); } else { notModified = containsValue(ifNoneMatch, eTag, null); } } } else if (first.startsWith("*") || (eTag != null && containsValue(ifNoneMatch, eTag, null))) { return HttpServletResponse.SC_PRECONDITION_FAILED; } } long ifModifiedSince = getRequestDateHeader(IF_MODIFIED_SINCE_HEADER); if (DAVHandlerFactory.METHOD_GET.equals(getRequestMethod()) && (notModified || ifNoneMatch == null) && ifModifiedSince != -1) { long requestTime = myRequest.getSession().getLastAccessedTime(); notModified = ifModifiedSince >= lastModifiedTime && ifModifiedSince <= requestTime; } if (notModified) { return HttpServletResponse.SC_NOT_MODIFIED; } return 0; } protected boolean containsValue(Enumeration values, String stringToFind, String matchAllString) { boolean contains = false; if (values != null) { while (values.hasMoreElements()) { String currentCondition = (String) values.nextElement(); contains = currentCondition.equals(stringToFind) || currentCondition.equals(matchAllString); if (contains) { break; } } } return contains; } protected boolean getSVNDiffVersion() { boolean diffCompress = false; for (Enumeration headerEncodings = getRequestHeaders(ACCEPT_ENCODING_HEADER); headerEncodings.hasMoreElements();) { String currentEncodings = (String) headerEncodings.nextElement(); String[] encodings = COMMA.split(currentEncodings); if (encodings.length > 1) { Arrays.sort(encodings, new Comparator() { public int compare(Object o1, Object o2) { String encoding1 = (String) o1; String encoding2 = (String) o2; return getEncodingRange(encoding1) > getEncodingRange(encoding2) ? 1 : -1; } }); for (int i = encodings.length - 1; i >= 0; i--) { if (DIFF_VERSION_1.equals(getEncodingName(encodings[i]))) { diffCompress = true; break; } else if (DIFF_VERSION.equals(getEncodingName(encodings[i]))) { break; } } } } return diffCompress; } protected FSCommitter getCommitter(FSFS fsfs, FSRoot root, FSTransactionInfo txn, Collection lockTokens, String userName) { myCommitter = new FSCommitter(fsfs, (FSTransactionRoot) root, txn, lockTokens, userName); return myCommitter; } protected FSDeltaConsumer getDeltaConsumer(FSRoot root, FSCommitter committer, FSFS fsfs, String userName, Collection lockTokens) { if (myDeltaConsumer == null) { myDeltaConsumer = new FSDeltaConsumer("", (FSTransactionRoot) root, fsfs, committer, userName, lockTokens); } return myDeltaConsumer; } private float getEncodingRange(String encoding) { int delimiterIndex = encoding.indexOf(";"); if (delimiterIndex != -1) { String qualityString = encoding.substring(delimiterIndex + 1); if (qualityString.startsWith("q=")) { try { return Float.parseFloat(qualityString.substring("q=".length())); } catch (NumberFormatException e) { } } } return 1.0f; } private String getEncodingName(String encoding) { int delimiterIndex = encoding.indexOf(";"); if (delimiterIndex != -1) { return encoding.substring(0, delimiterIndex); } return encoding; } private int meetsCondition(DAVResource resource, DAVResourceState resourceState) throws SVNException { Enumeration ifMatch = getRequestHeaders(IF_MATCH_HEADER); if (ifMatch != null && ifMatch.hasMoreElements()) { String first = (String) ifMatch.nextElement(); if (first.startsWith("*") && resourceState != DAVResourceState.EXISTS) { return HttpServletResponse.SC_PRECONDITION_FAILED; } } int retVal = checkPreconditions(resource.getETag(), resource.getLastModified()); if (retVal == HttpServletResponse.SC_PRECONDITION_FAILED) { Enumeration ifNoneMatch = getRequestHeaders(IF_NONE_MATCH_HEADER); if (ifNoneMatch != null && ifNoneMatch.hasMoreElements()) { String first = (String) ifNoneMatch.nextElement(); if (first.startsWith("*") && resourceState != DAVResourceState.EXISTS) { return 0; } } } return retVal; } protected long readInput(boolean ignoreInput) throws SVNException { if (ignoreInput) { InputStream inputStream = null; try { inputStream = getRequestInputStream(); while (inputStream.read() != -1) { continue; } } catch (IOException ioe) { // } finally { SVNFileUtil.closeFile(inputStream); } return -1; } if (mySAXParser == null) { CountingInputStream stream = null; try { mySAXParser = getSAXParserFactory().newSAXParser(); if (myRequest.getContentLength() > 0) { org.xml.sax.XMLReader reader = mySAXParser.getXMLReader(); reader.setContentHandler(this); reader.setDTDHandler(this); reader.setErrorHandler(this); reader.setEntityResolver(this); stream = new CountingInputStream(getRequestInputStream()); XMLReader xmlReader = new XMLReader(stream); reader.parse(new InputSource(xmlReader)); } } catch (ParserConfigurationException e) { if (stream == null || stream.getBytesRead() > 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } catch (SAXException e) { if (stream == null || stream.getBytesRead() > 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } catch (IOException e) { if (stream == null || stream.getBytesRead() > 0) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e), e, SVNLogType.NETWORK); } } if (stream != null) { if (stream.getBytesRead() > 0) { getDAVRequest().init(); } return stream.getBytesRead(); } } return 0; } //TODO: unused? protected void handleError(DAVException error, DAVResponse response) { if (response == null) { DAVException stackErr = error; while (stackErr != null && stackErr.getTagName() == null) { stackErr = stackErr.getPreviousException(); } if (stackErr != null && stackErr.getTagName() != null) { myResponse.setContentType(DEFAULT_XML_CONTENT_TYPE); StringBuffer errorMessageBuffer = new StringBuffer(); errorMessageBuffer.append('\n'); errorMessageBuffer.append("\n"); } else { errorMessageBuffer.append(">\n"); } if (stackErr.getMessage() != null) { } } } } protected HttpServletResponse getHttpServletResponse() { return myResponse; } public synchronized static SAXParserFactory getSAXParserFactory() { if (ourSAXParserFactory == null) { ourSAXParserFactory = SAXParserFactory.newInstance(); try { ourSAXParserFactory.setFeature("http://xml.org/sax/features/namespaces", true); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } try { ourSAXParserFactory.setFeature("http://xml.org/sax/features/validation", false); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } try { ourSAXParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } ourSAXParserFactory.setNamespaceAware(true); ourSAXParserFactory.setValidating(false); } return ourSAXParserFactory; } protected static class DAVAutoVersionInfo { private boolean myIsResourceVersioned; private boolean myIsResourceCheckedOut; private boolean myIsParentCheckedOut; private DAVResource myParentResource; public boolean isResourceVersioned() { return myIsResourceVersioned; } public void setResourceVersioned(boolean isResourceVersioned) { myIsResourceVersioned = isResourceVersioned; } public boolean isResourceCheckedOut() { return myIsResourceCheckedOut; } public void setResourceCheckedOut(boolean isResourceCheckedOut) { myIsResourceCheckedOut = isResourceCheckedOut; } public boolean isParentCheckedOut() { return myIsParentCheckedOut; } public void setParentCheckedOut(boolean isParentCheckedOut) { myIsParentCheckedOut = isParentCheckedOut; } public DAVResource getParentResource() { return myParentResource; } public void setParentResource(DAVResource parentResource) { myParentResource = parentResource; } } } svnkit-1.7.5+dfsg/svnkit-dav/src/main/webapp/000077500000000000000000000000001177510526000210445ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/webapp/WEB-INF/000077500000000000000000000000001177510526000220735ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-dav/src/main/webapp/WEB-INF/web.xml000066400000000000000000000053421177510526000233760ustar00rootroot00000000000000 DAV Subversion Servlet svnkit1 org.tmatesoft.svn.core.internal.server.dav.DAVServlet SVNParentPath %python.test.home%/python/cmdline/svn-test-work/repositories svnkit1 /svn-test-work/repositories/* svnkit2 org.tmatesoft.svn.core.internal.server.dav.DAVServlet SVNPath %python.test.home%/python/cmdline/svn-test-work/local_tmp/repos svnkit2 /svn-test-work/local_tmp/repos/* DAV SVNKit Security Constraint svnkit1 /svn-test-work/repositories/* tomcat DAV SVNKit Security Constraint svnkit2 /svn-test-work/local_tmp/repos/* tomcat BASIC SVNKit Repository Realm tomcat svnkit-1.7.5+dfsg/svnkit-distribution/000077500000000000000000000000001177510526000200205ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/build.gradle000066400000000000000000000075461177510526000223130ustar00rootroot00000000000000task buildAll << { File dstDir = new File(buildDir, "all") dstDir.mkdirs() copy { into new File(dstDir, "svnkit-${version}") into('lib') { from configurations.binaries.files eachFile fullJarNameExpander } into ('bin') { from configurations.scripts.files } into('src') { from configurations.sources.files } into('licenses') { from file('src/main/licenses') } from rootProject.files('LICENSE.txt', 'README.txt', 'CHANGES.txt') } File destfile = new File(distsDir, "svnkit-${version}-all.zip") ant.zip(destfile: destfile.absolutePath) { zipfileset(dir: dstDir.absolutePath, excludes: '**/bin/**') zipfileset(dir: dstDir.absolutePath, includes: '**/bin/**', excludes: '**/bin/*.bat', filemode: '755') zipfileset(dir: dstDir.absolutePath, includes: '**/bin/*.bat') } File destfileNoJNA = new File(distsDir, "svnkit-nojna-${version}-all.zip") ant.zip(destfile: destfileNoJNA.absolutePath) { zipfileset(dir: dstDir.absolutePath, excludes: '**/bin/**,**/jna*,**/LICENSE-JNA.txt') zipfileset(dir: dstDir.absolutePath, includes: '**/bin/**', excludes: '**/bin/*.bat', filemode: '755') zipfileset(dir: dstDir.absolutePath, includes: '**/bin/*.bat') } } task buildSources(type: Zip) { baseName = 'svnkit' classifier = 'src' into("svnkit-${version}") from rootProject.rootDir exclude '.*' exclude '**/.*' exclude '**/.*/**' exclude '**/build/**' exclude '**/bin/**' exclude '**/target/**' } task buildUpdateSite << { def tokens = new HashMap() File siteDir = new File(buildDir, 'site') File pluginsDir = new File(siteDir, 'plugins') File featuresDir = new File(siteDir, 'features') pluginsDir.mkdirs() configurations.osgi.resolvedConfiguration.each { conf -> conf.resolvedArtifacts.each { artifact -> if (artifact.file.name.endsWith('.zip') || artifact.file.name.endsWith('.jar')) { org.tmatesoft.build.BuildVersion fileVersion = org.tmatesoft.build.BuildVersion.fromJarFile(artifact.file) String name = artifact.getModuleVersion().getId().getName() name = name.replace('-', '_') tokens[name + '_version'] = fileVersion.bundleVersion tokens[name + '_name'] = fileVersion.bundleSymbolicName tokens[name + '_fullName'] = fullJarName(artifact.file) copy { from artifact.file into pluginsDir eachFile fullJarNameExpander } } } } copy { into siteDir from 'src/main/update-site' include 'site.xml' expand(tokens) } file('src/main/update-site/features').listFiles().each { if (it.isDirectory()) { String fullName = tokens[it.name.replace('-', '_') + '_fullName'] if (fullName != null) { makeFeatureJar(it, new File(featuresDir, fullName), tokens) } } } distsDir.mkdirs() File destfile = new File(distsDir, "svnkit-update-site-${version}.zip") ant.zip(destfile: destfile.absolutePath, basedir: siteDir.absolutePath) } def makeFeatureJar(File dir, File dstFile, Map tokens) { def tmpDir = new File(buildDir, 'tmp/' + dstFile.getName()) tmpDir.mkdirs() copy { into tmpDir from dir expand(tokens) } ant.jar(destfile: dstFile.absolutePath, basedir: tmpDir.absolutePath) } buildAll.dependsOn tasks.clean buildAll.dependsOn configurations.binaries buildAll.dependsOn configurations.scripts buildAll.dependsOn configurations.sources buildUpdateSite.dependsOn configurations.osgi task build(dependsOn: [buildAll, buildUpdateSite, buildSources]) svnkit-1.7.5+dfsg/svnkit-distribution/src/000077500000000000000000000000001177510526000206075ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/src/main/000077500000000000000000000000001177510526000215335ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/src/main/licenses/000077500000000000000000000000001177510526000233405ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/src/main/licenses/LICENSE-ANTLR.txt000066400000000000000000000026201177510526000260410ustar00rootroot00000000000000[The "BSD licence"] Copyright (c) 2003-2008 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. svnkit-1.7.5+dfsg/svnkit-distribution/src/main/licenses/LICENSE-JAVAHL.txt000066400000000000000000000052711177510526000261330ustar00rootroot00000000000000This license applies to all portions of Subversion which are not externally-maintained libraries (e.g. apr/, apr-util/, and neon/). Such libraries have their own licenses; we recommend you read them, as their terms may differ from the terms below. This is version 1 of this license. It is also available online at http://subversion.tigris.org/license-1.html. If newer versions of this license are posted there (the same URL, but with the version number incremented: .../license-2.html, .../license-3.html, and so on), you may use a newer version instead, at your option. ==================================================================== Copyright (c) 2000-2005 CollabNet. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by CollabNet (http://www.Collab.Net/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The hosted project names must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact info@collab.net. 5. Products derived from this software may not use the "Tigris" name nor may "Tigris" appear in their names without prior written permission of CollabNet. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COLLABNET OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==================================================================== This software consists of voluntary contributions made by many individuals on behalf of CollabNet. svnkit-1.7.5+dfsg/svnkit-distribution/src/main/licenses/LICENSE-JNA.txt000066400000000000000000000010401177510526000255640ustar00rootroot00000000000000Copyright (c) 2008 Timothy Wall, All Rights Reserved This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.svnkit-1.7.5+dfsg/svnkit-distribution/src/main/licenses/LICENSE-SEQUENCE.txt000066400000000000000000000043441177510526000263760ustar00rootroot00000000000000Sequence Library License This license applies to all portions of the Sequence library, which are not externally-maintained libraries (e.g. junit or jsch). ==================================================================== Copyright (c) 2000-2008 SyntEvo GmbH, Ainring, GERMANY. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by SyntEvo GmbH, Ainring, GERMANY." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The hosted project names must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact info@syntevo.com. 5. Neither the name of SyntEvo GmbH nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SyntEvo GmbH OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==================================================================== svnkit-1.7.5+dfsg/svnkit-distribution/src/main/licenses/LICENSE-SQLJET.txt000066400000000000000000000015721177510526000261700ustar00rootroot00000000000000Copyright (C) 2009-2010 TMate Software Ltd As part of SVNKit library, SQLJet library is distributed under the terms of TMate Open Source License (see http://svnkit.com/license.html). Otherwise, outside of SVNKit library, the following licensing terms are applicable for SQLJet library: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. For information on how to redistribute this software under the terms of a license other than GNU General Public License contact TMate Software at support@sqljet.comsvnkit-1.7.5+dfsg/svnkit-distribution/src/main/licenses/LICENSE-TRILEAD.txt000066400000000000000000000110101177510526000262360ustar00rootroot00000000000000Copyright (c) 2007-2008 Trilead AG (http://www.trilead.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: a.) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b.) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. c.) Neither the name of Trilead nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Trilead SSH-2 for Java includes code that was written by Dr. Christian Plattner during his PhD at ETH Zurich. The license states the following: Copyright (c) 2005 - 2006 Swiss Federal Institute of Technology (ETH Zurich), Department of Computer Science (http://www.inf.ethz.ch), Christian Plattner. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: a.) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b.) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. c.) Neither the name of ETH Zurich nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The Java implementations of the AES, Blowfish and 3DES ciphers have been taken (and slightly modified) from the cryptography package released by "The Legion Of The Bouncy Castle". Their license states the following: Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/000077500000000000000000000000001177510526000237575ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/features/000077500000000000000000000000001177510526000255755ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/features/jna-osgi/000077500000000000000000000000001177510526000273045ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/features/jna-osgi/feature.properties000066400000000000000000000016451177510526000330630ustar00rootroot00000000000000license=Copyright (c) 2008 Timothy Wall, All Rights Reserved\\n\\ \\n\\ This library is free software; you can redistribute it and/or\\n\\ modify it under the terms of the GNU Lesser General Public\\n\\ License as published by the Free Software Foundation; either\\n\\ version 2.1 of the License, or (at your option) any later version.\\n\\ \\n\\ This library is distributed in the hope that it will be useful,\\n\\ but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\\ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\\n\\ Lesser General Public License for more details. description=JNA provides Java programs easy access to native shared libraries \\ (DLLs on Windows) without writing anything but Java code - no JNI \\ or native code is required. This functionality is comparable \\ to Windows' Platform/Invoke and Python's ctypes. \\ Access is dynamic at runtime without code generation. svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/features/jna-osgi/feature.xml000066400000000000000000000015501177510526000314620ustar00rootroot00000000000000 JNA Library Copyright (c) 2008 Timothy Wall, All Rights Reserved %license svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/features/svnkit-osgi/000077500000000000000000000000001177510526000300525ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/features/svnkit-osgi/feature.properties000066400000000000000000000057341177510526000336340ustar00rootroot00000000000000license=The TMate Open Source License\\n\\ \\n\\ This license applies to all portions of TMate SVNKit library, which\\n\\ are not externally-maintained libraries (e.g. Trilead SSH library).\\n\\ \\n\\ All the source code and compiled classes in package org.tigris.subversion.javahl\\n\\ except SvnClient class are covered by the license in JAVAHL-LICENSE file\\n\\ \\n\\ Copyright (c) 2004-2011 TMate Software. All rights reserved.\\n\\ \\n\\ Redistribution and use in source and binary forms, with or without modification,\\n\\ are permitted provided that the following conditions are met:\\n\\ \\n\\ * Redistributions of source code must retain the above copyright notice,\\n\\ this list of conditions and the following disclaimer.\\n\\ \\n\\ * Redistributions in binary form must reproduce the above copyright notice,\\n\\ this list of conditions and the following disclaimer in the documentation \\n\\ and/or other materials provided with the distribution.\\n\\ \\n\\ * Redistributions in any form must be accompanied by information on how to\\n\\ obtain complete source code for the software that uses SVNKit and any \\n\\ accompanying software that uses the software that uses SVNKit. The source\\n\\ code must either be included in the distribution or be available for no \\n\\ more than the cost of distribution plus a nominal fee, and must be freely \\n\\ redistributable under reasonable conditions. For an executable file, complete\\n\\ source code means the source code for all modules it contains. It does not \\n\\ include source code for modules or files that typically accompany the major \\n\\ components of the operating system on which the executable file runs.\\n\\ \\n\\ * Redistribution in any form without redistributing source code for software\\n\\ that uses SVNKit is possible only when such redistribution is explictly permitted\\n\\ by TMate Software. Please, contact TMate Software at support@svnkit.com to \\n\\ get such permission.\\n\\ \\n\\ THIS SOFTWARE IS PROVIDED BY TMATE SOFTWARE ``AS IS'' AND ANY EXPRESS OR IMPLIED\\n\\ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \\n\\ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE\\n\\ DISCLAIMED. \\n\\ \\n\\ IN NO EVENT SHALL TMATE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,\\n\\ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\\n\\ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR \\n\\ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \\n\\ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\\n\\ OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \\n\\ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\\n\\ \\n description=SVNKit is a pure java Subversion client library that may be used through its own API or serve as a transparent replacement of native javahl bindings.svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/features/svnkit-osgi/feature.xml000066400000000000000000000022431177510526000322300ustar00rootroot00000000000000 %description (c) 2004-2011, TMate Software Ltd. %license svnkit-1.7.5+dfsg/svnkit-distribution/src/main/update-site/site.xml000066400000000000000000000021301177510526000254410ustar00rootroot00000000000000 TMate Sofware SVNKit Library Update Site SVNKit Library Includes JNA Library plugin which is optionally used by SVNKit to improve performance of certain low-level filesystem operations and to implement some additional features. JNA Library is licensed under the terms of LGPL. It is strongly recommened to install JNA Library, unless you could not accept LGPL software in your environment. svnkit-1.7.5+dfsg/svnkit-javahl16/000077500000000000000000000000001177510526000167155ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/build.gradle000066400000000000000000000045771177510526000212110ustar00rootroot00000000000000project.ext.srcRoot = file('src/main/java') testClasses << { def resolvedArtifact = configurations.testCompile.resolvedConfiguration.resolvedArtifacts.find { it.name == 'svn-javahl-tests' } copy { from zipTree(resolvedArtifact.file) into sourceSets.test.output.classesDir } } classes << { def resolvedArtifact = configurations.testCompile.resolvedConfiguration.resolvedArtifacts.find { it.name == 'svn-javahl-api' } copy { from zipTree(resolvedArtifact.file) into sourceSets.main.output.classesDir exclude 'META-INF/**' eachFile { details -> if (details.isDirectory()) { return } else if (details.name.endsWith('.class')) { String javaFilePath = details.path javaFilePath = javaFilePath.substring(0, javaFilePath.lastIndexOf('.')) while (javaFilePath.indexOf('$') > 0) { javaFilePath = javaFilePath.substring(0, javaFilePath.lastIndexOf('$')) } File candidate = new File(srcRoot, javaFilePath + '.java') if (candidate.exists()) { details.exclude() } } } } } test { includes = ['**/tigris/subversion/javahl/BasicTests*', '**/tigris/subversion/javahl/SVNAdminTests*'] //does not pass on Windows: BasicTests.testBasicChangelist systemProperty 'svnkit.wc.17', 'false' ignoreFailures = true workingDir = file('build/tests-working-dir') } task testJavaHL2(type: Test) { includes = ['*/apache/subversion/javahl/BasicTests*'] //does not pass on Windows: BasicTests.testBasicChangelist ignoreFailures = true workingDir = file('build/tests-working-dir') enableAssertions = true } test.doFirst() { mkdir('build/tests-working-dir') } testJavaHL2.doFirst() { mkdir('build/tests-working-dir') } configurations { javahlSources } dependencies { javahlSources group: 'org.tigris.subversion', name: 'svn-javahl-api', version: '1.6.18-v2', classifier: 'sources' } sourcesJar { into('') { from configurations.javahlSources.files.collect { zipTree(it) } exclude 'META-INF/**' eachFile { f -> if (new File(srcRoot, f.path).exists()) { f.exclude() } } } } sourcesJar.dependsOn configurations.javahlSources svnkit-1.7.5+dfsg/svnkit-javahl16/src/000077500000000000000000000000001177510526000175045ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/000077500000000000000000000000001177510526000204305ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/000077500000000000000000000000001177510526000213515ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/000077500000000000000000000000001177510526000221405ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/apache/000077500000000000000000000000001177510526000233615ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/apache/subversion/000077500000000000000000000000001177510526000255605ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/apache/subversion/javahl/000077500000000000000000000000001177510526000270255ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/apache/subversion/javahl/SVNClient.java000066400000000000000000000363431177510526000315060ustar00rootroot00000000000000package org.apache.subversion.javahl; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.subversion.javahl.callback.BlameCallback; import org.apache.subversion.javahl.callback.ChangelistCallback; import org.apache.subversion.javahl.callback.ClientNotifyCallback; import org.apache.subversion.javahl.callback.CommitCallback; import org.apache.subversion.javahl.callback.CommitMessageCallback; import org.apache.subversion.javahl.callback.ConflictResolverCallback; import org.apache.subversion.javahl.callback.DiffSummaryCallback; import org.apache.subversion.javahl.callback.InfoCallback; import org.apache.subversion.javahl.callback.ListCallback; import org.apache.subversion.javahl.callback.LogMessageCallback; import org.apache.subversion.javahl.callback.PatchCallback; import org.apache.subversion.javahl.callback.ProgressCallback; import org.apache.subversion.javahl.callback.ProplistCallback; import org.apache.subversion.javahl.callback.StatusCallback; import org.apache.subversion.javahl.callback.UserPasswordCallback; import org.apache.subversion.javahl.types.CopySource; import org.apache.subversion.javahl.types.Depth; import org.apache.subversion.javahl.types.Mergeinfo; import org.apache.subversion.javahl.types.Revision; import org.apache.subversion.javahl.types.RevisionRange; import org.apache.subversion.javahl.types.Version; import org.tmatesoft.svn.core.javahl17.SVNClientImpl; public class SVNClient implements ISVNClient { private SVNClientImpl delegate; public SVNClient() { delegate = SVNClientImpl.newInstance(); } public void dispose() { delegate.dispose(); } public Version getVersion() { return delegate.getVersion(); } public String getAdminDirectoryName() { return delegate.getAdminDirectoryName(); } public boolean isAdminDirectory(String name) { return delegate.isAdminDirectory(name); } public void status(String path, Depth depth, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals, Collection changelists, StatusCallback callback) throws ClientException { delegate.status(path, depth, onServer, getAll, noIgnore, ignoreExternals, changelists, callback); } public void list(String url, Revision revision, Revision pegRevision, Depth depth, int direntFields, boolean fetchLocks, ListCallback callback) throws ClientException { delegate.list(url, revision, pegRevision, depth, direntFields, fetchLocks, callback); } public void username(String username) { delegate.username(username); } public void password(String password) { delegate.password(password); } public void setPrompt(UserPasswordCallback prompt) { delegate.setPrompt(prompt); } public void logMessages(String path, Revision pegRevision, List ranges, boolean stopOnCopy, boolean discoverPath, boolean includeMergedRevisions, Set revProps, long limit, LogMessageCallback callback) throws ClientException { delegate.logMessages(path, pegRevision, ranges, stopOnCopy, discoverPath, includeMergedRevisions, revProps, limit, callback); } public long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, Depth depth, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { return delegate.checkout(moduleName, destPath, revision, pegRevision, depth, ignoreExternals, allowUnverObstructions); } public void notification2(ClientNotifyCallback notify) { delegate.notification2(notify); } public void setConflictResolver(ConflictResolverCallback listener) { delegate.setConflictResolver(listener); } public void setProgressCallback(ProgressCallback listener) { delegate.setProgressCallback(listener); } public void remove(Set path, boolean force, boolean keepLocal, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { delegate.remove(path, force, keepLocal, revpropTable, handler, callback); } public void revert(String path, Depth depth, Collection changelists) throws ClientException { delegate.revert(path, depth, changelists); } public void add(String path, Depth depth, boolean force, boolean noIgnores, boolean addParents) throws ClientException { delegate.add(path, depth, force, noIgnores, addParents); } public long[] update(Set path, Revision revision, Depth depth, boolean depthIsSticky, boolean makeParents, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { return delegate.update(path, revision, depth, depthIsSticky, makeParents, ignoreExternals, allowUnverObstructions); } public void commit(Set path, Depth depth, boolean noUnlock, boolean keepChangelist, Collection changelists, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { delegate.commit(path, depth, noUnlock, keepChangelist, changelists, revpropTable, handler, callback); } public void copy(List sources, String destPath, boolean copyAsChild, boolean makeParents, boolean ignoreExternals, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { delegate.copy(sources, destPath, copyAsChild, makeParents, ignoreExternals, revpropTable, handler, callback); } public void move(Set srcPaths, String destPath, boolean force, boolean moveAsChild, boolean makeParents, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { delegate.move(srcPaths, destPath, force, moveAsChild, makeParents, revpropTable, handler, callback); } public void mkdir(Set path, boolean makeParents, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { delegate.mkdir(path, makeParents, revpropTable, handler, callback); } public void cleanup(String path) throws ClientException { delegate.cleanup(path); } public void resolve(String path, Depth depth, ConflictResult.Choice conflictResult) throws SubversionException { delegate.resolve(path, depth, conflictResult); } public long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, Depth depth, String nativeEOL) throws ClientException { return delegate.doExport(srcPath, destPath, revision, pegRevision, force, ignoreExternals, depth, nativeEOL); } public long doSwitch(String path, String url, Revision revision, Revision pegRevision, Depth depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions, boolean ignoreAncestry) throws ClientException { return delegate.doSwitch(path, url, revision, pegRevision, depth, depthIsSticky, ignoreExternals, allowUnverObstructions, ignoreAncestry); } public void doImport(String path, String url, Depth depth, boolean noIgnore, boolean ignoreUnknownNodeTypes, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { delegate.doImport(path, url, depth, noIgnore, ignoreUnknownNodeTypes, revpropTable, handler, callback); } public Set suggestMergeSources(String path, Revision pegRevision) throws SubversionException { return delegate.suggestMergeSources(path, pegRevision); } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, Depth depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { delegate.merge(path1, revision1, path2, revision2, localPath, force, depth, ignoreAncestry, dryRun, recordOnly); } public void merge(String path, Revision pegRevision, List revisions, String localPath, boolean force, Depth depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { delegate.merge(path, pegRevision, revisions, localPath, force, depth, ignoreAncestry, dryRun, recordOnly); } public void mergeReintegrate(String path, Revision pegRevision, String localPath, boolean dryRun) throws ClientException { delegate.mergeReintegrate(path, pegRevision, localPath, dryRun); } public Mergeinfo getMergeinfo(String path, Revision pegRevision) throws SubversionException { return delegate.getMergeinfo(path, pegRevision); } public void getMergeinfoLog(Mergeinfo.LogKind kind, String pathOrUrl, Revision pegRevision, String mergeSourceUrl, Revision srcPegRevision, boolean discoverChangedPaths, Depth depth, Set revProps, LogMessageCallback callback) throws ClientException { delegate.getMergeinfoLog(kind, pathOrUrl, pegRevision, mergeSourceUrl, srcPegRevision, discoverChangedPaths, depth, revProps, callback); } public void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, String outFileName, Depth depth, Collection changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { delegate.diff(target1, revision1, target2, revision2, relativeToDir, outFileName, depth, changelists, ignoreAncestry, noDiffDeleted, force, copiesAsAdds); } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, String outFileName, Depth depth, Collection changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { delegate.diff(target, pegRevision, startRevision, endRevision, relativeToDir, outFileName, depth, changelists, ignoreAncestry, noDiffDeleted, force, copiesAsAdds); } public void diffSummarize(String target1, Revision revision1, String target2, Revision revision2, Depth depth, Collection changelists, boolean ignoreAncestry, DiffSummaryCallback receiver) throws ClientException { delegate.diffSummarize(target1, revision1, target2, revision2, depth, changelists, ignoreAncestry, receiver); } public void diffSummarize(String target, Revision pegRevision, Revision startRevision, Revision endRevision, Depth depth, Collection changelists, boolean ignoreAncestry, DiffSummaryCallback receiver) throws ClientException { delegate.diffSummarize(target, pegRevision, startRevision, endRevision, depth, changelists, ignoreAncestry, receiver); } public void properties(String path, Revision revision, Revision pegRevision, Depth depth, Collection changelists, ProplistCallback callback) throws ClientException { delegate.properties(path, revision, pegRevision, depth, changelists, callback); } public void propertySetLocal(Set paths, String name, byte[] value, Depth depth, Collection changelists, boolean force) throws ClientException { delegate.propertySetLocal(paths, name, value, depth, changelists, force); } public void propertySetRemote(String path, long baseRev, String name, byte[] value, CommitMessageCallback handler, boolean force, Map revpropTable, CommitCallback callback) throws ClientException { delegate.propertySetRemote(path, baseRev, name, value, handler, force, revpropTable, callback); } public byte[] revProperty(String path, String name, Revision rev) throws ClientException { return delegate.revProperty(path, name, rev); } public Map revProperties(String path, Revision rev) throws ClientException { return delegate.revProperties(path, rev); } public void setRevProperty(String path, String name, Revision rev, String value, String originalValue, boolean force) throws ClientException { delegate.setRevProperty(path, name, rev, value, originalValue, force); } public byte[] propertyGet(String path, String name, Revision revision, Revision pegRevision) throws ClientException { return delegate.propertyGet(path, name, revision, pegRevision); } public byte[] fileContent(String path, Revision revision, Revision pegRevision) throws ClientException { return delegate.fileContent(path, revision, pegRevision); } public void streamFileContent(String path, Revision revision, Revision pegRevision, OutputStream stream) throws ClientException { delegate.streamFileContent(path, revision, pegRevision, stream); } public void relocate(String from, String to, String path, boolean ignoreExternals) throws ClientException { delegate.relocate(from, to, path, ignoreExternals); } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, BlameCallback callback) throws ClientException { delegate.blame(path, pegRevision, revisionStart, revisionEnd, ignoreMimeType, includeMergedRevisions, callback); } public void setConfigDirectory(String configDir) throws ClientException { delegate.setConfigDirectory(configDir); } public String getConfigDirectory() throws ClientException { return delegate.getConfigDirectory(); } public void cancelOperation() throws ClientException { delegate.cancelOperation(); } public void addToChangelist(Set paths, String changelist, Depth depth, Collection changelists) throws ClientException { delegate.addToChangelist(paths, changelist, depth, changelists); } public void removeFromChangelists(Set paths, Depth depth, Collection changelists) throws ClientException { delegate.removeFromChangelists(paths, depth, changelists); } public void getChangelists(String rootPath, Collection changelists, Depth depth, ChangelistCallback callback) throws ClientException { delegate.getChangelists(rootPath, changelists, depth, callback); } public void lock(Set path, String comment, boolean force) throws ClientException { delegate.lock(path, comment, force); } public void unlock(Set path, boolean force) throws ClientException { delegate.unlock(path, force); } public void info2(String pathOrUrl, Revision revision, Revision pegRevision, Depth depth, Collection changelists, InfoCallback callback) throws ClientException { delegate.info2(pathOrUrl, revision, pegRevision, depth, changelists, callback); } public String getVersionInfo(String path, String trailUrl, boolean lastChanged) throws ClientException { return delegate.getVersionInfo(path, trailUrl, lastChanged); } public void upgrade(String path) throws ClientException { delegate.upgrade(path); } public void patch(String patchPath, String targetPath, boolean dryRun, int stripCount, boolean reverse, boolean ignoreWhitespace, boolean removeTempfiles, PatchCallback callback) throws ClientException { delegate.patch(patchPath, targetPath, dryRun, stripCount, reverse, ignoreWhitespace, removeTempfiles, callback); } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/apache/subversion/javahl/SVNRepos.java000066400000000000000000000072111177510526000313500ustar00rootroot00000000000000package org.apache.subversion.javahl; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import org.apache.subversion.javahl.callback.ReposNotifyCallback; import org.apache.subversion.javahl.types.Depth; import org.apache.subversion.javahl.types.Lock; import org.apache.subversion.javahl.types.Revision; import org.apache.subversion.javahl.types.Version; import org.tmatesoft.svn.core.javahl17.SVNReposImpl; public class SVNRepos implements ISVNRepos { private SVNReposImpl delegate; public SVNRepos() { this.delegate = new SVNReposImpl(); } public void dispose() { delegate.dispose(); } public Version getVersion() { return delegate.getVersion(); } public void create(File path, boolean disableFsyncCommit, boolean keepLog, File configPath, String fstype) throws ClientException { delegate.create(path, disableFsyncCommit, keepLog, configPath, fstype); } public void deltify(File path, Revision start, Revision end) throws ClientException { delegate.deltify(path, start, end); } public void dump(File path, OutputStream dataOut, Revision start, Revision end, boolean incremental, boolean useDeltas, ReposNotifyCallback callback) throws ClientException { delegate.dump(path, dataOut, start, end, incremental, useDeltas, callback); } public void hotcopy(File path, File targetPath, boolean cleanLogs) throws ClientException { delegate.hotcopy(path, targetPath, cleanLogs); } public void listDBLogs(File path, MessageReceiver receiver) throws ClientException { delegate.listDBLogs(path, receiver); } public void listUnusedDBLogs(File path, MessageReceiver receiver) throws ClientException { delegate.listUnusedDBLogs(path, receiver); } public void load(File path, InputStream dataInput, boolean ignoreUUID, boolean forceUUID, boolean usePreCommitHook, boolean usePostCommitHook, String relativePath, ReposNotifyCallback callback) throws ClientException { delegate.load(path, dataInput, ignoreUUID, forceUUID, usePreCommitHook, usePostCommitHook, relativePath, callback); } public void lstxns(File path, MessageReceiver receiver) throws ClientException { delegate.lstxns(path, receiver); } public long recover(File path, ReposNotifyCallback callback) throws ClientException { return delegate.recover(path, callback); } public void rmtxns(File path, String[] transactions) throws ClientException { delegate.rmtxns(path, transactions); } public void setRevProp(File path, Revision rev, String propName, String propValue, boolean usePreRevPropChangeHook, boolean usePostRevPropChangeHook) throws SubversionException { delegate.setRevProp(path, rev, propName, propValue, usePreRevPropChangeHook, usePostRevPropChangeHook); } public void verify(File path, Revision start, Revision end, ReposNotifyCallback callback) throws ClientException { delegate.verify(path, start, end, callback); } public Set lslocks(File path, Depth depth) throws ClientException { return delegate.lslocks(path, depth); } public void rmlocks(File path, String[] locks) throws ClientException { delegate.rmlocks(path, locks); } public void upgrade(File path, ReposNotifyCallback callback) throws ClientException { delegate.upgrade(path, callback); } public void pack(File path, ReposNotifyCallback callback) throws ClientException { delegate.pack(path, callback); } public void cancelOperation() throws ClientException { delegate.cancelOperation(); } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/000077500000000000000000000000001177510526000234415ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/subversion/000077500000000000000000000000001177510526000256405ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/subversion/javahl/000077500000000000000000000000001177510526000271055ustar00rootroot00000000000000JavaHLObjectFactory.java000066400000000000000000001147521177510526000334670ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/subversion/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tigris.subversion.javahl; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.SVNLogEntryPath; import org.tmatesoft.svn.core.SVNMergeRange; import org.tmatesoft.svn.core.SVNMergeRangeList; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNConflictVersion; import org.tmatesoft.svn.core.io.SVNLocationEntry; import org.tmatesoft.svn.core.javahl.SVNClientImpl; import org.tmatesoft.svn.core.wc.SVNCommitItem; import org.tmatesoft.svn.core.wc.SVNConflictAction; import org.tmatesoft.svn.core.wc.SVNConflictChoice; import org.tmatesoft.svn.core.wc.SVNConflictDescription; import org.tmatesoft.svn.core.wc.SVNConflictReason; import org.tmatesoft.svn.core.wc.SVNConflictResult; import org.tmatesoft.svn.core.wc.SVNDiffStatus; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc.SVNInfo; import org.tmatesoft.svn.core.wc.SVNMergeFileSet; import org.tmatesoft.svn.core.wc.SVNOperation; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNRevisionRange; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNTreeConflictDescription; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class JavaHLObjectFactory { private static final Map STATUS_CONVERSION_MAP = new SVNHashMap(); private static final Map REVISION_KIND_CONVERSION_MAP = new SVNHashMap(); private static final Map ACTION_CONVERSION_MAP = new SVNHashMap(); private static final Map LOCK_CONVERSION_MAP = new SVNHashMap(); private static final Map CONFLICT_REASON_CONVERSATION_MAP = new SVNHashMap(); private static final Comparator CHANGE_PATH_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { ChangePath cp1 = (ChangePath) o1; ChangePath cp2 = (ChangePath) o2; return SVNPathUtil.PATH_COMPARATOR.compare(cp1.getPath(), cp2.getPath()); } }; static{ STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_ADDED, new Integer(StatusKind.added)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_CONFLICTED, new Integer(StatusKind.conflicted)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_DELETED, new Integer(StatusKind.deleted)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_EXTERNAL, new Integer(StatusKind.external)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_IGNORED, new Integer(StatusKind.ignored)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_INCOMPLETE, new Integer(StatusKind.incomplete)); //STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_MERGED, new Integer(StatusKind.merged)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_MISSING, new Integer(StatusKind.missing)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_MODIFIED, new Integer(StatusKind.modified)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_NONE, new Integer(StatusKind.none)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_NORMAL, new Integer(StatusKind.normal)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_OBSTRUCTED, new Integer(StatusKind.obstructed)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_REPLACED, new Integer(StatusKind.replaced)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_UNVERSIONED, new Integer(StatusKind.unversioned)); STATUS_CONVERSION_MAP.put(SVNStatusType.STATUS_NAME_CONFLICT, new Integer(StatusKind.unversioned)); STATUS_CONVERSION_MAP.put(SVNStatusType.CHANGED, new Integer(NotifyStatus.changed)); STATUS_CONVERSION_MAP.put(SVNStatusType.CONFLICTED, new Integer(NotifyStatus.conflicted)); STATUS_CONVERSION_MAP.put(SVNStatusType.INAPPLICABLE, new Integer(NotifyStatus.inapplicable)); STATUS_CONVERSION_MAP.put(SVNStatusType.MERGED, new Integer(NotifyStatus.merged)); STATUS_CONVERSION_MAP.put(SVNStatusType.MISSING, new Integer(NotifyStatus.missing)); STATUS_CONVERSION_MAP.put(SVNStatusType.OBSTRUCTED, new Integer(NotifyStatus.obstructed)); STATUS_CONVERSION_MAP.put(SVNStatusType.UNCHANGED, new Integer(NotifyStatus.unchanged)); STATUS_CONVERSION_MAP.put(SVNStatusType.UNKNOWN, new Integer(NotifyStatus.unknown)); LOCK_CONVERSION_MAP.put(SVNStatusType.LOCK_INAPPLICABLE, new Integer(LockStatus.inapplicable)); LOCK_CONVERSION_MAP.put(SVNStatusType.LOCK_LOCKED, new Integer(LockStatus.locked)); LOCK_CONVERSION_MAP.put(SVNStatusType.LOCK_UNCHANGED, new Integer(LockStatus.unchanged)); LOCK_CONVERSION_MAP.put(SVNStatusType.LOCK_UNKNOWN, new Integer(LockStatus.unknown)); LOCK_CONVERSION_MAP.put(SVNStatusType.LOCK_UNLOCKED, new Integer(LockStatus.unlocked)); REVISION_KIND_CONVERSION_MAP.put(new Integer(RevisionKind.base), SVNRevision.BASE); REVISION_KIND_CONVERSION_MAP.put(new Integer(RevisionKind.committed), SVNRevision.COMMITTED); REVISION_KIND_CONVERSION_MAP.put(new Integer(RevisionKind.head), SVNRevision.HEAD); REVISION_KIND_CONVERSION_MAP.put(new Integer(RevisionKind.previous), SVNRevision.PREVIOUS); REVISION_KIND_CONVERSION_MAP.put(new Integer(RevisionKind.unspecified), SVNRevision.UNDEFINED); REVISION_KIND_CONVERSION_MAP.put(new Integer(RevisionKind.working), SVNRevision.WORKING); ACTION_CONVERSION_MAP.put(SVNEventAction.ADD, new Integer(NotifyAction.add)); ACTION_CONVERSION_MAP.put(SVNEventAction.ANNOTATE, new Integer(NotifyAction.blame_revision)); ACTION_CONVERSION_MAP.put(SVNEventAction.COMMIT_ADDED, new Integer(NotifyAction.commit_added)); ACTION_CONVERSION_MAP.put(SVNEventAction.COMMIT_DELETED, new Integer(NotifyAction.commit_deleted)); ACTION_CONVERSION_MAP.put(SVNEventAction.COMMIT_DELTA_SENT, new Integer(NotifyAction.commit_postfix_txdelta)); ACTION_CONVERSION_MAP.put(SVNEventAction.COMMIT_MODIFIED, new Integer(NotifyAction.commit_modified)); ACTION_CONVERSION_MAP.put(SVNEventAction.COMMIT_REPLACED, new Integer(NotifyAction.commit_replaced)); ACTION_CONVERSION_MAP.put(SVNEventAction.COPY, new Integer(NotifyAction.copy)); ACTION_CONVERSION_MAP.put(SVNEventAction.DELETE, new Integer(NotifyAction.delete)); ACTION_CONVERSION_MAP.put(SVNEventAction.FAILED_REVERT, new Integer(NotifyAction.failed_revert)); ACTION_CONVERSION_MAP.put(SVNEventAction.LOCK_FAILED, new Integer(NotifyAction.failed_lock)); ACTION_CONVERSION_MAP.put(SVNEventAction.LOCKED, new Integer(NotifyAction.locked)); //ACTION_CONVERSION_MAP.put(SVNEventAction.PROGRESS, new Integer(NotifyAction.)); ACTION_CONVERSION_MAP.put(SVNEventAction.RESOLVED, new Integer(NotifyAction.resolved)); ACTION_CONVERSION_MAP.put(SVNEventAction.RESTORE, new Integer(NotifyAction.restore)); ACTION_CONVERSION_MAP.put(SVNEventAction.REVERT, new Integer(NotifyAction.revert)); ACTION_CONVERSION_MAP.put(SVNEventAction.SKIP, new Integer(NotifyAction.skip)); ACTION_CONVERSION_MAP.put(SVNEventAction.STATUS_COMPLETED, new Integer(NotifyAction.status_completed)); ACTION_CONVERSION_MAP.put(SVNEventAction.STATUS_EXTERNAL, new Integer(NotifyAction.status_external)); ACTION_CONVERSION_MAP.put(SVNEventAction.UNLOCK_FAILED, new Integer(NotifyAction.failed_unlock)); ACTION_CONVERSION_MAP.put(SVNEventAction.UNLOCKED, new Integer(NotifyAction.unlocked)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_ADD, new Integer(NotifyAction.update_add)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_COMPLETED, new Integer(NotifyAction.update_completed)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_DELETE, new Integer(NotifyAction.update_delete)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_EXTERNAL, new Integer(NotifyAction.update_external)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_UPDATE, new Integer(NotifyAction.update_update)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_NONE, new Integer(NotifyAction.update_update)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_EXISTS, new Integer(NotifyAction.exists)); ACTION_CONVERSION_MAP.put(SVNEventAction.UPDATE_REPLACE, new Integer(NotifyAction.update_replaced)); ACTION_CONVERSION_MAP.put(SVNEventAction.CHANGELIST_SET, new Integer(NotifyAction.changelist_set)); ACTION_CONVERSION_MAP.put(SVNEventAction.CHANGELIST_CLEAR, new Integer(NotifyAction.changelist_clear)); ACTION_CONVERSION_MAP.put(SVNEventAction.MERGE_BEGIN, new Integer(NotifyAction.merge_begin)); ACTION_CONVERSION_MAP.put(SVNEventAction.FOREIGN_MERGE_BEGIN, new Integer(NotifyAction.foreign_merge_begin)); ACTION_CONVERSION_MAP.put(SVNEventAction.PROPERTY_ADD, new Integer(NotifyAction.property_added)); ACTION_CONVERSION_MAP.put(SVNEventAction.PROPERTY_MODIFY, new Integer(NotifyAction.property_modified)); ACTION_CONVERSION_MAP.put(SVNEventAction.PROPERTY_DELETE, new Integer(NotifyAction.property_deleted)); ACTION_CONVERSION_MAP.put(SVNEventAction.PROPERTY_DELETE_NONEXISTENT, new Integer(NotifyAction.property_deleted_nonexistent)); ACTION_CONVERSION_MAP.put(SVNEventAction.REVPROPER_SET, new Integer(NotifyAction.revprop_set)); ACTION_CONVERSION_MAP.put(SVNEventAction.REVPROP_DELETE, new Integer(NotifyAction.revprop_deleted)); ACTION_CONVERSION_MAP.put(SVNEventAction.MERGE_COMPLETE, new Integer(NotifyAction.merge_completed)); ACTION_CONVERSION_MAP.put(SVNEventAction.TREE_CONFLICT, new Integer(NotifyAction.tree_conflict)); // undocumented thing. ACTION_CONVERSION_MAP.put(SVNEventAction.COMMIT_COMPLETED, new Integer(-11)); CONFLICT_REASON_CONVERSATION_MAP.put(SVNConflictReason.ADDED, new Integer(ConflictDescriptor.Reason.added)); CONFLICT_REASON_CONVERSATION_MAP.put(SVNConflictReason.DELETED, new Integer(ConflictDescriptor.Reason.deleted)); CONFLICT_REASON_CONVERSATION_MAP.put(SVNConflictReason.EDITED, new Integer(ConflictDescriptor.Reason.edited)); CONFLICT_REASON_CONVERSATION_MAP.put(SVNConflictReason.MISSING, new Integer(ConflictDescriptor.Reason.missing)); CONFLICT_REASON_CONVERSATION_MAP.put(SVNConflictReason.OBSTRUCTED, new Integer(ConflictDescriptor.Reason.obstructed)); CONFLICT_REASON_CONVERSATION_MAP.put(SVNConflictReason.UNVERSIONED, new Integer(ConflictDescriptor.Reason.unversioned)); } public static Collection getChangeListsCollection(String[] changelists) { if (changelists != null) { return Arrays.asList(changelists); } return null; } public static Status createStatus(String path, SVNStatus status) { if (status == null){ return null; } String url = status.getURL() != null ? status.getURL().toString() : null; if (url == null && status.getEntryProperties() != null) { url = (String) status.getEntryProperties().get(SVNProperty.URL); } if (url == null && status.getRemoteURL() != null) { url = status.getRemoteURL().toString(); } int nodeKind = getNodeKind(status.getKind()); if (status.getContentsStatus() == SVNStatusType.STATUS_IGNORED) { nodeKind = NodeKind.unknown; } long revision = status.getRevision().getNumber(); long lastChangedRevision = -1; if(status.getCommittedRevision() != null){ lastChangedRevision = status.getCommittedRevision().getNumber(); } Date d = status.getCommittedDate(); long lastChangedDate = -1; if(d != null){ lastChangedDate = d.getTime() * 1000; } String lastCommitAuthor = status.getAuthor(); int textStatus = getStatusValue(status.getContentsStatus()); int propStatus = getStatusValue(status.getPropertiesStatus()); int repositoryTextStatus = getStatusValue(status.getRemoteContentsStatus()); int repositoryPropStatus = getStatusValue(status.getRemotePropertiesStatus()); boolean locked = status.isLocked(); boolean copied = status.isCopied(); boolean switched = status.isSwitched(); String conflictOld = null; if(status.getConflictOldFile()!=null){ conflictOld = status.getConflictOldFile().getName(); } String conflictNew = null; if(status.getConflictNewFile()!=null){ conflictNew = status.getConflictNewFile().getName(); } String conflictWorking = null; if(status.getConflictWrkFile()!=null){ conflictWorking = status.getConflictWrkFile().getName(); } String urlCopiedFrom = status.getCopyFromURL(); long revisionCopiedFrom = status.getCopyFromRevision().getNumber(); String lockToken = null; String lockOwner = null; String lockComment = null; long lockCreationDate = 0; if(status.getLocalLock() != null){ lockToken = status.getLocalLock().getID(); lockOwner = status.getLocalLock().getOwner(); lockComment = status.getLocalLock().getComment(); lockCreationDate = status.getLocalLock().getCreationDate().getTime() * 1000; } Lock reposLock = createLock(status.getRemoteLock()); if (path != null) { path = path.replace(File.separatorChar, '/'); } long reposRev = status.getRemoteRevision() != null ? status.getRemoteRevision().getNumber() : -1; long reposDate = status.getRemoteDate() != null ? status.getRemoteDate().getTime() * 1000 : -1; String reposAuthor = status.getRemoteAuthor(); int reposKind = getNodeKind(status.getRemoteKind()); if (status.getRemoteKind() == null) { reposKind = NodeKind.none; } SVNTreeConflictDescription tc = status.getTreeConflict(); Status st = new Status(path, url, nodeKind, revision, lastChangedRevision, lastChangedDate, lastCommitAuthor, textStatus, propStatus, repositoryTextStatus, repositoryPropStatus, locked, copied, tc != null, createConflictDescription(tc), conflictOld, conflictNew, conflictWorking, urlCopiedFrom, revisionCopiedFrom, switched, false, lockToken, lockOwner, lockComment, lockCreationDate, reposLock, /* remote: rev, date, kind, author */ reposRev, reposDate, reposKind, reposAuthor, status.getChangelistName()); return st; } public static SVNRevision getSVNRevision(Revision r){ if(r == null){ return SVNRevision.UNDEFINED; } else if(r.getKind() == RevisionKind.number){ return SVNRevision.create(((Revision.Number)r).getNumber()); } else if(r.getKind() == RevisionKind.date){ return SVNRevision.create(((Revision.DateSpec)r).getDate()); } return (SVNRevision)REVISION_KIND_CONVERSION_MAP.get(new Integer(r.getKind())); } public static SVNDepth getSVNDepth(int depth) { switch (depth) { case Depth.empty: return SVNDepth.EMPTY; case Depth.exclude: return SVNDepth.EXCLUDE; case Depth.files: return SVNDepth.FILES; case Depth.immediates: return SVNDepth.IMMEDIATES; case Depth.infinity: return SVNDepth.INFINITY; default: return SVNDepth.UNKNOWN; } } public static ConflictDescriptor createConflictDescription(SVNConflictDescription conflictDescription) { if (conflictDescription == null){ return null; } SVNMergeFileSet mergeFiles = conflictDescription.getMergeFiles(); String basePath = null; String repositoryPath = null; try { basePath = mergeFiles.getBasePath(); repositoryPath = mergeFiles.getRepositoryPath(); } catch (SVNException e) { // } ConflictVersion left = null; ConflictVersion right = null; int op = 0; if (conflictDescription.isTreeConflict()) { SVNTreeConflictDescription tc = (SVNTreeConflictDescription) conflictDescription; left = createConflictVersion(tc.getSourceLeftVersion()); right = createConflictVersion(tc.getSourceRightVersion()); op = getConflictOperation(tc.getOperation()); } return new ConflictDescriptor(mergeFiles.getWCPath(), getConflictKind(conflictDescription.isPropertyConflict()), getNodeKind(conflictDescription.getNodeKind()), conflictDescription.getPropertyName(), mergeFiles.isBinary(), mergeFiles.getMimeType(), getConflictAction(conflictDescription.getConflictAction()), getConflictReason(conflictDescription.getConflictReason()), op, basePath, repositoryPath, mergeFiles.getWCPath(), mergeFiles.getResultPath(), left, right ); } private static int getConflictOperation(SVNOperation operation) { if (operation == SVNOperation.MERGE) { return Operation.merge; } else if (operation == SVNOperation.NONE) { return Operation.none; } else if (operation == SVNOperation.UPDATE) { return Operation.update; } else if (operation == SVNOperation.SWITCH) { return Operation.switched; } return Operation.none; } private static ConflictVersion createConflictVersion(SVNConflictVersion version) { if (version == null) { return null; } String url = version.getRepositoryRoot() != null ? version.getRepositoryRoot().toString() : null; return new ConflictVersion(url, version.getPegRevision(), version.getPath(), getNodeKind(version.getKind())); } public static SVNConflictResult getSVNConflictResult(ConflictResult conflictResult) { if (conflictResult == null){ return null; } return new SVNConflictResult(getSVNConflictChoice(conflictResult.getChoice()), conflictResult.getMergedPath() != null ? new File(conflictResult.getMergedPath()).getAbsoluteFile() : null); } public static int getConflictAction(SVNConflictAction conflictAction){ if (conflictAction == SVNConflictAction.ADD){ return ConflictDescriptor.Action.add; } else if (conflictAction == SVNConflictAction.DELETE) { return ConflictDescriptor.Action.delete; } else if (conflictAction == SVNConflictAction.EDIT) { return ConflictDescriptor.Action.edit; } return -1; } public static SVNConflictChoice getSVNConflictChoice(int conflictResult){ switch (conflictResult) { case ConflictResult.chooseBase: return SVNConflictChoice.BASE; case ConflictResult.chooseMerged: return SVNConflictChoice.MERGED; case ConflictResult.chooseMineConflict: return SVNConflictChoice.MINE_CONFLICT; case ConflictResult.chooseMineFull: return SVNConflictChoice.MINE_FULL; case ConflictResult.chooseTheirsConflict: return SVNConflictChoice.THEIRS_CONFLICT; case ConflictResult.chooseTheirsFull: return SVNConflictChoice.THEIRS_FULL; case ConflictResult.postpone: return SVNConflictChoice.POSTPONE; default: return null; } } public static int getConflictReason(SVNConflictReason conflictReason){ Object reason = CONFLICT_REASON_CONVERSATION_MAP.get(conflictReason); if (reason != null){ return ((Integer) reason).intValue(); } return -1; } public static int getConflictKind(boolean isPropertyConflict){ return isPropertyConflict ? ConflictDescriptor.Kind.property : ConflictDescriptor.Kind.text; } public static DiffSummary createDiffSummary(SVNDiffStatus status) { int diffStatus = -1; if (status.getModificationType() == SVNStatusType.STATUS_NORMAL || status.getModificationType() == SVNStatusType.STATUS_NONE) { diffStatus = 0; } else if (status.getModificationType() == SVNStatusType.STATUS_ADDED) { diffStatus = 1; } else if (status.getModificationType() == SVNStatusType.STATUS_MODIFIED) { diffStatus = 2; } else if (status.getModificationType() == SVNStatusType.STATUS_DELETED) { diffStatus = 3; } return new DiffSummary(status.getPath(), diffStatus, status.isPropertiesModified(), getNodeKind(status.getKind())); } public static int getNodeKind(SVNNodeKind svnKind){ if(svnKind == SVNNodeKind.DIR ){ return NodeKind.dir; } else if(svnKind == SVNNodeKind.NONE ){ return NodeKind.none; } else if(svnKind == SVNNodeKind.FILE ){ return NodeKind.file; } return NodeKind.unknown; } public static int getStatusValue(SVNStatusType svnStatusType){ Object status = STATUS_CONVERSION_MAP.get(svnStatusType); if(status == null){ return -1; } return ((Integer)status).intValue(); } public static int getLockStatusValue(SVNStatusType svnStatusType){ Object status = LOCK_CONVERSION_MAP.get(svnStatusType); if(status == null){ return -1; } return ((Integer)status).intValue(); } public static int getNotifyActionValue(SVNEventAction action){ Object status = ACTION_CONVERSION_MAP.get(action); if(status == null){ return -1; } return ((Integer)status).intValue(); } public static DirEntry createDirEntry(SVNDirEntry dirEntry) { if(dirEntry == null){ return null; } SVNURL url = dirEntry.getURL(); SVNURL repositoryRoot = dirEntry.getRepositoryRoot(); String relativeToRepositoryRoot = SVNPathUtil.getRelativePath(repositoryRoot.getPath(), url.getPath()); String relativeToTargetPath = dirEntry.getRelativePath(); String targetToRootPath = relativeToRepositoryRoot.substring(0, relativeToRepositoryRoot.length() - relativeToTargetPath.length()); return new DirEntry( relativeToTargetPath, SVNPathUtil.getAbsolutePath(targetToRootPath), getNodeKind(dirEntry.getKind()), dirEntry.getSize(), dirEntry.hasProperties(), dirEntry.getRevision(), dirEntry.getDate() != null ? dirEntry.getDate().getTime()*1000 : 0, dirEntry.getAuthor() ); } public static LogMessage createLogMessage(SVNLogEntry logEntry) { if(logEntry == null){ return null; } Map cpaths = logEntry.getChangedPaths(); ChangePath[] cp = null; if(cpaths == null){ cp = new ChangePath[]{}; }else{ Collection clientChangePaths = new ArrayList(); for (Iterator iter = cpaths.keySet().iterator(); iter.hasNext();) { String path = (String) iter.next(); SVNLogEntryPath entryPath = (SVNLogEntryPath)cpaths.get(path); if(entryPath != null){ clientChangePaths.add(new ChangePath(path, entryPath.getCopyRevision(), entryPath.getCopyPath(), entryPath.getType(), getNodeKind(entryPath.getKind()))); } } cp = (ChangePath[]) clientChangePaths.toArray(new ChangePath[clientChangePaths.size()]); // sort by paths. Arrays.sort(cp, CHANGE_PATH_COMPARATOR); } long time = 0; if (logEntry.getDate() != null) { time = logEntry.getDate().getTime()*1000; if (logEntry.getDate() instanceof SVNDate) { time = ((SVNDate) logEntry.getDate()).getTimeInMicros(); } } return new LogMessage(cp, logEntry.getRevision(), logEntry.getAuthor(), time, logEntry.getMessage()); } public static Mergeinfo createMergeInfo(Map mergeInfo) { if (mergeInfo == null) { return null; } Mergeinfo result = new Mergeinfo(); for (Iterator iterator = mergeInfo.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); SVNURL mergeSrcURL = (SVNURL) entry.getKey(); String url = mergeSrcURL.toString(); SVNMergeRangeList rangeList = (SVNMergeRangeList) entry.getValue(); SVNMergeRange[] ranges = rangeList.getRanges(); for (int i = 0; i < ranges.length; i++) { SVNMergeRange range = ranges[i]; result.addRevisionRange(url, createRevisionRange(range)); } } return result; } public static RevisionRange createRevisionRange(SVNMergeRange range){ if (range == null){ return null; } return new RevisionRange(new Revision.Number(range.getStartRevision()), new Revision.Number(range.getEndRevision())); } public static RevisionRange[] createRevisionRanges(SVNMergeRangeList rangeList) { if (rangeList == null) { return null; } SVNMergeRange[] ranges = rangeList.getRanges(); RevisionRange[] result = new RevisionRange[ranges.length]; for (int i = 0; i < ranges.length; i++) { result[i] = createRevisionRange(ranges[i]); } return result; } public static SVNRevisionRange getSVNRevisionRange(RevisionRange revisionRange) { return new SVNRevisionRange(getSVNRevision(revisionRange.getFromRevision()), getSVNRevision(revisionRange.getToRevision())); } public static void handleLogMessage(SVNLogEntry logEntry, LogMessageCallback handler) { if(logEntry == null || handler == null) { return; } Map cpaths = logEntry.getChangedPaths(); ChangePath[] cp = null; if (cpaths == null) { cp = new ChangePath[]{}; } else { Collection clientChangePaths = new ArrayList(); for (Iterator iter = cpaths.keySet().iterator(); iter.hasNext();) { String path = (String) iter.next(); SVNLogEntryPath entryPath = (SVNLogEntryPath)cpaths.get(path); if(entryPath != null){ clientChangePaths.add(new ChangePath(path, entryPath.getCopyRevision(), entryPath.getCopyPath(), entryPath.getType(), getNodeKind(entryPath.getKind()))); } } cp = (ChangePath[]) clientChangePaths.toArray(new ChangePath[clientChangePaths.size()]); } SVNProperties revisionProperties = logEntry.getRevisionProperties(); Map revisionPropertiesMap = new HashMap(); for(Iterator names = revisionProperties.nameSet().iterator(); names.hasNext();) { String name = (String) names.next(); revisionPropertiesMap.put(name, revisionProperties.getStringValue(name)); } handler.singleMessage(cp, logEntry.getRevision(), revisionPropertiesMap, logEntry.hasChildren()); } public static CommitItem[] getCommitItems(SVNCommitItem[] commitables, boolean isImport, boolean isURLsOnly) { if (commitables == null) { return null; } CommitItem[] items = new CommitItem[commitables.length]; for (int i = 0; i < items.length; i++) { SVNCommitItem sc = commitables[i]; if(sc == null) { items[i] = null; } else { int stateFlag = 0; if (sc.isDeleted()) { stateFlag += CommitItemStateFlags.Delete; } if (sc.isAdded()) { stateFlag += CommitItemStateFlags.Add; } if (sc.isContentsModified()) { stateFlag += CommitItemStateFlags.TextMods; } if (sc.isPropertiesModified()) { stateFlag += CommitItemStateFlags.PropMods; } if(sc.isCopied()){ stateFlag += CommitItemStateFlags.IsCopy; } String url = sc.getURL() != null ? sc.getURL().toString() : null; String path = isURLsOnly ? null : sc.getFile() != null ? sc.getFile().getAbsolutePath() : null; if (path != null) { path = path.replace(File.separatorChar, '/'); } if (path != null && isImport) { url = null; } int kind = isImport ? NodeKind.none : getNodeKind(sc.getKind()); items[i] = new CommitItem(path, kind, stateFlag, url, sc.getCopyFromURL() != null ? sc.getCopyFromURL().toString() : null, sc.getRevision().getNumber()); } } return items; } public static Lock createLock(SVNLock svnLock){ if(svnLock == null){ return null; } return new Lock(svnLock.getOwner(), svnLock.getPath(), svnLock.getID(), svnLock.getComment(), svnLock.getCreationDate() != null ? svnLock.getCreationDate().getTime() * 1000 : 0, svnLock.getExpirationDate() != null ? svnLock.getExpirationDate().getTime() * 1000 : 0); } public static Info createInfo(SVNInfo info) { if(info == null){ return null; } int schedule = ScheduleKind.normal; if (SVNProperty.SCHEDULE_ADD.equals(info.getSchedule())) { schedule = ScheduleKind.add; } else if (SVNProperty.SCHEDULE_DELETE.equals(info.getSchedule())) { schedule = ScheduleKind.delete; } File file = info.getFile(); boolean deleted = file != null && !file.exists() && schedule == ScheduleKind.delete; boolean absent = file != null && !deleted && !file.exists(); boolean incomplete = false; long copyRev = info.getCopyFromRevision() != null ? info.getCopyFromRevision().getNumber(): - 1; String copyUrl = info.getCopyFromURL() != null ? info.getCopyFromURL().toString() : null; String path = info.getFile() != null ? info.getFile().getName() : SVNPathUtil.tail(info.getPath()); if (path != null) { path = path.replace(File.separatorChar, '/'); } return new Info( path, info.getURL() != null ? info.getURL().toString() : null, info.getRepositoryUUID(), info.getRepositoryRootURL() != null ? info.getRepositoryRootURL().toString() : null, schedule, getNodeKind(info.getKind()), info.getAuthor(), info.getRevision() != null ? info.getRevision().getNumber() : -1, info.getCommittedRevision() != null ? info.getCommittedRevision().getNumber() : - 1, info.getCommittedDate(), info.getTextTime(), info.getPropTime(), info.getCopyFromRevision() != null || info.getCopyFromURL()!=null, deleted, absent, incomplete, copyRev, copyUrl ); } public static Info2 createInfo2(SVNInfo info) { if(info == null){ return null; } int schedule = ScheduleKind.normal; if (SVNProperty.SCHEDULE_ADD.equals(info.getSchedule())) { schedule = ScheduleKind.add; } else if (SVNProperty.SCHEDULE_DELETE.equals(info.getSchedule())) { schedule = ScheduleKind.delete; } long copyRev = info.getCopyFromRevision() != null ? info.getCopyFromRevision().getNumber() : -1; String copyUrl = info.getCopyFromURL() != null ? info.getCopyFromURL().toString() : null; String path = info.getFile() != null ? info.getFile().getAbsolutePath() : info.getPath(); if (path != null) { path = path.replace(File.separatorChar, '/'); } int depth = info.getDepth() != null ? info.getDepth().getId() : Depth.unknown; if (info.getKind() == SVNNodeKind.FILE) { depth = 0; } return new Info2( path, info.getURL() != null ? info.getURL().toString() : null, info.getRevision() != null ? info.getRevision().getNumber() : -1, getNodeKind(info.getKind()), info.getRepositoryRootURL() != null ? info.getRepositoryRootURL().toString() : null, info.getRepositoryUUID(), info.getCommittedRevision() != null ? info.getCommittedRevision().getNumber() : - 1, info.getCommittedDate() != null ? info.getCommittedDate().getTime() * 1000 : 0, info.getAuthor(), createLock(info.getLock()), !info.isRemote(), schedule, copyUrl, copyRev, info.getTextTime() != null ? info.getTextTime().getTime() * 1000 : 0, info.getPropTime() != null ? info.getPropTime().getTime() * 1000 : 0, info.getChecksum(), info.getConflictOldFile() != null ? info.getConflictOldFile().getName() : null, info.getConflictNewFile() != null ? info.getConflictNewFile().getName() : null, info.getConflictWrkFile() != null ? info.getConflictWrkFile().getName() : null, info.getPropConflictFile() != null ? info.getPropConflictFile().getName() : null, info.getChangelistName(), info.getWorkingSize(), info.getRepositorySize(), depth, createConflictDescription(info.getTreeConflict()) ); } public static ProgressEvent createProgressEvent(long onProgress, long total) { return new ProgressEvent(onProgress, total); } public static PropertyData createPropertyData(Object client, String path, String name, SVNPropertyValue value) { if (client instanceof SVNClientImpl){ if (value.isString()) { return new JavaHLPropertyData((SVNClientImpl) client, null, path, name, value.getString(), SVNPropertyValue.getPropertyAsBytes(value)); } return new JavaHLPropertyData((SVNClientImpl) client, null, path, name, SVNPropertyValue.getPropertyAsString(value), value.getBytes()); } if (value.isString()) { return new PropertyData((SVNClient) client, path, name, value.getString(), SVNPropertyValue.getPropertyAsBytes(value)); } return new PropertyData((SVNClient) client, path, name, SVNPropertyValue.getPropertyAsString(value), value.getBytes()); } public static NotifyInformation createNotifyInformation(SVNEvent event, String path) { final int actionId = getNotifyActionValue(event.getAction()); if (actionId == -1) { return null; } // include full error message. String errMsg = null; if (event.getErrorMessage() != null) { errMsg = event.getErrorMessage().getFullMessage(); } // TODO 16 return new NotifyInformation( path, actionId, getNodeKind(event.getNodeKind()), event.getMimeType(), createLock(event.getLock()), errMsg, getStatusValue(event.getContentsStatus()), getStatusValue(event.getPropertiesStatus()), getLockStatusValue(event.getLockStatus()), event.getRevision(), event.getChangelistName(), createRevisionRange(event.getMergeRange()), "" ); } public static CopySource createCopySource(SVNLocationEntry location) { return new CopySource(location.getPath(), Revision.getInstance(location.getRevision()), null); } public static Level getLoggingLevel(int level) { if (level == SVNClientLogLevel.NoLog) { return Level.OFF; } else if (level == SVNClientLogLevel.ErrorLog) { return Level.SEVERE; } else if (level == SVNClientLogLevel.ExceptionLog) { return Level.FINE; } else if (level == SVNClientLogLevel.EntryLog) { return Level.FINEST; } return Level.OFF; } public static void throwException(SVNException e, SVNClientImpl svnClient) throws ClientException { int code = 0; if (e.getErrorMessage() != null) { code = e.getErrorMessage().getErrorCode().getCode(); } ClientException ec = new ClientException(e.getMessage(), null, code); ec.initCause(e); svnClient.getDebugLog().logFine(SVNLogType.DEFAULT, ec); svnClient.getDebugLog().logFine(SVNLogType.DEFAULT, e); throw ec; } public static final int infinityOrEmpty(boolean recurse) { return Depth.infinityOrEmpty(recurse); } public static final int infinityOrFiles(boolean recurse) { return Depth.infinityOrFiles(recurse); } public static final int infinityOrImmediates(boolean recurse) { return Depth.infinityOrImmediates(recurse); } public static final int unknownOrFiles(boolean recurse) { return Depth.unknownOrFiles(recurse); } public static final int unknownOrImmediates(boolean recurse) { return Depth.unknownOrImmediates(recurse); } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/subversion/javahl/JavaHLPropertyData.java000066400000000000000000000033331177510526000334160ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tigris.subversion.javahl; import org.tmatesoft.svn.core.javahl.SVNClientImpl; /** * @version 1.3 * @author TMate Software Ltd. */ public class JavaHLPropertyData extends PropertyData { private SVNClientImpl myClientImpl; JavaHLPropertyData(SVNClientImpl clientImpl, SVNClient cl, String p, String n, String v, byte[] d) { super(cl, p, n, v, d); myClientImpl = clientImpl; } public void remove(boolean recurse) throws ClientException { if (myClientImpl != null) { myClientImpl.propertyRemove(getPath(), getName(), recurse); } else { super.remove(recurse); } } public void setValue(byte[] newValue, boolean recurse) throws ClientException { if (myClientImpl != null) { myClientImpl.propertySet(getPath(), getName(), newValue, recurse); } else { super.setValue(newValue, recurse); } } public void setValue(String newValue, boolean recurse) throws ClientException { if (myClientImpl != null) { myClientImpl.propertySet(getPath(), getName(), newValue, recurse); } else { super.setValue(newValue, recurse); } } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/subversion/javahl/Path.java000066400000000000000000000023331177510526000306450ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tigris.subversion.javahl; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; /** * @version 1.3 * @author TMate Software Ltd. */ public class Path { public static boolean isValid(String path) { if (path == null) { return false; } for(int i = 0; i < path.length(); i++) { char ch = path.charAt(i); if (SVNEncodingUtil.isASCIIControlChar(ch)) { return false; } } return true; } public static boolean isURL(String path) { if (path == null) { throw new IllegalArgumentException(); } return (path.indexOf("://") > 0); } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/subversion/javahl/SVNAdmin.java000066400000000000000000000546321177510526000314010ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tigris.subversion.javahl; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.javahl.SVNClientImpl; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAdapter; import org.tmatesoft.svn.core.wc.admin.SVNUUIDAction; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNAdmin { protected long cppAddr; private SVNClientImpl myDelegate; private SVNAdminClient mySVNAdminClient; /** * Filesystem in a Berkeley DB */ public static final String BDB = "bdb"; /** * Filesystem in the filesystem */ public static final String FSFS = "fsfs"; public SVNAdmin() { myDelegate = SVNClientImpl.newInstance(); } public void dispose() { myDelegate.dispose(); mySVNAdminClient = null; } /** * @return Version information about the underlying native libraries. */ public Version getVersion() { return myDelegate.getVersion(); } protected SVNAdminClient getAdminClient() { if (mySVNAdminClient == null) { mySVNAdminClient = new SVNAdminClient(SVNWCUtil.createDefaultAuthenticationManager(), SVNWCUtil.createDefaultOptions(true)); } return mySVNAdminClient; } /** * create a subversion repository. * * @param path the path where the repository will been * created. * @param disableFsyncCommit disable to fsync at the commit (BDB). * @param keepLog keep the log files (BDB). * @param configPath optional path for user configuration files. * @param fstype the type of the filesystem (BDB or FSFS) * @throws ClientException throw in case of problem */ public void create(String path, boolean disableFsyncCommit, boolean keepLog, String configPath, String fstype) throws ClientException { if (BDB.equalsIgnoreCase(fstype)) { notImplementedYet("Only " + FSFS + " type of repositories are supported by " + getVersion().toString()); } try { SVNRepositoryFactory.createLocalRepository(new File(path), false, false); if (configPath != null) { } } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } } /** * deltify the revisions in the repository * * @param path the path to the repository * @param start start revision * @param end end revision * @throws ClientException throw in case of problem */ public void deltify(String path, Revision start, Revision end) throws ClientException { notImplementedYet(); } /** * dump the data in a repository * * @param path the path to the repository * @param dataOut the data will be outputed here * @param errorOut the messages will be outputed here * @param start the first revision to be dumped * @param end the last revision to be dumped * @param incremental the dump will be incremantal * @throws ClientException throw in case of problem */ public void dump(String path, OutputInterface dataOut, OutputInterface errorOut, Revision start, Revision end, boolean incremental) throws ClientException { dump(path, dataOut, errorOut, start, end, incremental, false); } /** * dump the data in a repository * * @param path the path to the repository * @param dataOut the data will be outputed here * @param errorOut the messages will be outputed here * @param start the first revision to be dumped * @param end the last revision to be dumped * @param incremental the dump will be incremantal * @param useDeltas the dump will contain deltas between nodes * @throws ClientException throw in case of problem * @since 1.5 */ public void dump(String path, OutputInterface dataOut, final OutputInterface errorOut, Revision start, Revision end, boolean incremental, boolean useDeltas) throws ClientException { OutputStream os = createOutputStream(dataOut); try { getAdminClient().setEventHandler(new SVNAdminEventAdapter() { public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (errorOut != null && event.getAction() == SVNAdminEventAction.REVISION_DUMPED) { try { errorOut.write(event.getMessage().getBytes()); errorOut.write(myDelegate.getOptions().getNativeEOL()); } catch (IOException e) { } } } }); getAdminClient().doDump(new File(path).getAbsoluteFile(), os, JavaHLObjectFactory.getSVNRevision(start), JavaHLObjectFactory.getSVNRevision(end), incremental, useDeltas); } catch (SVNException e) { try { if (errorOut != null) { errorOut.write(e.getErrorMessage().getFullMessage().getBytes("UTF-8")); errorOut.write(myDelegate.getOptions().getNativeEOL()); } } catch (IOException e1) { // } JavaHLObjectFactory.throwException(e, myDelegate); } finally { getAdminClient().setEventHandler(null); } } /** * make a hot copy of the repository * * @param path the path to the source repository * @param targetPath the path to the target repository * @param cleanLogs clean the unused log files in the source * repository * @throws ClientException throw in case of problem */ public void hotcopy(String path, String targetPath, boolean cleanLogs) throws ClientException { try { getAdminClient().doHotCopy(new File(path).getAbsoluteFile(), new File(targetPath).getAbsoluteFile()); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } } /** * list all logfiles (BDB) in use or not) * * @param path the path to the repository * @param receiver interface to receive the logfile names * @throws ClientException throw in case of problem */ public void listDBLogs(String path, MessageReceiver receiver) throws ClientException { notImplementedYet("Only " + FSFS + " type of repositories are supported by " + getVersion().toString()); } /** * list unused logfiles * * @param path the path to the repository * @param receiver interface to receive the logfile names * @throws ClientException throw in case of problem */ public void listUnusedDBLogs(String path, MessageReceiver receiver) throws ClientException { notImplementedYet("Only " + FSFS + " type of repositories are supported by " + getVersion().toString()); } /** * interface to receive the messages */ public static interface MessageReceiver { /** * receive one message line * * @param message one line of message */ public void receiveMessageLine(String message); } /** * load the data of a dump into a repository, * * @param path the path to the repository * @param dataInput the data input source * @param messageOutput the target for processing messages * @param ignoreUUID ignore any UUID found in the input stream * @param forceUUID set the repository UUID to any found in the * stream * @param relativePath the directory in the repository, where the data * in put optional. * @throws ClientException throw in case of problem */ public void load(String path, InputInterface dataInput, final OutputInterface messageOutput, boolean ignoreUUID, boolean forceUUID, String relativePath) throws ClientException { load(path, dataInput, messageOutput, ignoreUUID, forceUUID, false, false, relativePath); } public void load(String path, InputInterface dataInput, final OutputInterface messageOutput, boolean ignoreUUID, boolean forceUUID, boolean usePreCommitHook, boolean usePostCommitHook, String relativePath) throws ClientException { InputStream is = createInputStream(dataInput); try { SVNUUIDAction uuidAction = SVNUUIDAction.DEFAULT; if (ignoreUUID) { uuidAction = SVNUUIDAction.IGNORE_UUID; } else if (forceUUID) { uuidAction = SVNUUIDAction.FORCE_UUID; } getAdminClient().setEventHandler(new SVNAdminEventAdapter() { private boolean myIsNodeOpened; public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (messageOutput != null) { try { messageOutput.write(getLoadMessage(event).getBytes("UTF-8")); } catch (IOException e) { } } } protected String getLoadMessage(SVNAdminEvent event) { StringBuffer message = new StringBuffer(); if (event.getAction() != SVNAdminEventAction.REVISION_LOAD && myIsNodeOpened) { message.append(" done."); message.append(myDelegate.getOptions().getNativeEOL()); myIsNodeOpened = false; } if (event.getAction() == SVNAdminEventAction.REVISION_LOADED) { message.append(myDelegate.getOptions().getNativeEOL()); } message.append(event.getMessage()); message.append(myDelegate.getOptions().getNativeEOL()); if (event.getAction() == SVNAdminEventAction.REVISION_LOADED) { message.append(myDelegate.getOptions().getNativeEOL()); } myIsNodeOpened = event.getAction() != SVNAdminEventAction.REVISION_LOAD; return message.toString(); } }); getAdminClient().doLoad(new File(path).getAbsoluteFile(), is, usePreCommitHook, usePostCommitHook, uuidAction, relativePath); } catch (SVNException e) { if (messageOutput != null) { try { messageOutput.write(e.getErrorMessage().getFullMessage().getBytes("UTF-8")); messageOutput.write(myDelegate.getOptions().getNativeEOL()); } catch (IOException e1) { } } JavaHLObjectFactory.throwException(e, myDelegate); } finally { getAdminClient().setEventHandler(null); } } /** * list all open transactions in a repository * * @param path the path to the repository * @param receiver receives one transaction name per call * @throws ClientException throw in case of problem */ public void lstxns(String path, final MessageReceiver receiver) throws ClientException { getAdminClient().setEventHandler(new SVNAdminEventAdapter() { public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (receiver != null && event.getTxnName() != null) { receiver.receiveMessageLine(event.getTxnName()); } } }); try { getAdminClient().doListTransactions(new File(path).getAbsoluteFile()); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } finally { getAdminClient().setEventHandler(null); } } /** * recover the berkeley db of a repository, returns youngest revision * * @param path the path to the repository * @throws ClientException throw in case of problem */ public long recover(String path) throws ClientException { try { File repositoryRoot = new File(path).getAbsoluteFile(); getAdminClient().doRecover(repositoryRoot); return getAdminClient().getYoungestRevision(repositoryRoot); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } return -1; } /** * remove open transaction in a repository * * @param path the path to the repository * @param transactions the transactions to be removed * @throws ClientException throw in case of problem */ public void rmtxns(String path, String[] transactions) throws ClientException { try { getAdminClient().doRemoveTransactions(new File(path).getAbsoluteFile(), transactions); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } } /** * set the log message of a revision * * @param path the path to the repository * @param rev the revision to be changed * @param message the message to be set * @param bypassHooks if to bypass all repository hooks * @throws ClientException throw in case of problem * @deprecated Use setRevProp() instead. */ public void setLog(String path, Revision rev, String message, boolean bypassHooks) throws ClientException { try { setRevisionProperty(path, rev, SVNRevisionProperty.LOG, message, bypassHooks, bypassHooks); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } } /** * Change the value of the revision property propName * to propValue. By default, does not run * pre-/post-revprop-change hook scripts. * * @param path The path to the repository. * @param rev The revision for which to change a property value. * @param propName The name of the property to change. * @param propValue The new value to set for the property. * @param usePreRevPropChangeHook Whether to run the * pre-revprop-change hook script. * @param usePostRevPropChangeHook Whether to run the * post-revprop-change hook script. * @throws SubversionException If a problem occurs. * @since 1.5.0 */ public void setRevProp(String path, Revision rev, String propName, String propValue, boolean usePreRevPropChangeHook, boolean usePostRevPropChangeHook) throws SubversionException { try { setRevisionProperty(path, rev, propName, propValue, !usePreRevPropChangeHook, !usePostRevPropChangeHook); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } } private static void setRevisionProperty(String path, Revision rev, String propName, String propValue, boolean bypassPreRevPropChangeHook, boolean bypassPostRevPropChangeHook) throws SVNException { SVNRepository repository = SVNRepositoryFactory.create(SVNURL.fromFile(new File(path).getAbsoluteFile())); ((FSRepository) repository).setRevisionPropertyValue(JavaHLObjectFactory.getSVNRevision(rev).getNumber(), propName, SVNPropertyValue.create(propValue), bypassPreRevPropChangeHook, bypassPostRevPropChangeHook); } /** * verify the repository * * @param path the path to the repository * @param messageOut the receiver of all messages * @param start the first revision * @param end the last revision * @throws ClientException throw in case of problem */ public void verify(String path, final OutputInterface messageOut, Revision start, Revision end) throws ClientException { try { getAdminClient().setEventHandler(new SVNAdminEventAdapter() { public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (messageOut != null && event.getAction() == SVNAdminEventAction.REVISION_DUMPED) { try { messageOut.write(event.getMessage().getBytes()); messageOut.write(myDelegate.getOptions().getNativeEOL()); } catch (IOException e) { } } } }); getAdminClient().doVerify(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(start), JavaHLObjectFactory.getSVNRevision(end)); } catch (SVNException e) { try { if (messageOut != null) { messageOut.write(e.getErrorMessage().getFullMessage().getBytes("UTF-8")); messageOut.write(myDelegate.getOptions().getNativeEOL()); } } catch (IOException e1) { // } JavaHLObjectFactory.throwException(e, myDelegate); } finally { getAdminClient().setEventHandler(null); } } /** * list all locks in the repository * * @param path the path to the repository * @throws ClientException throw in case of problem * @since 1.2 */ public Lock[] lslocks(String path) throws ClientException { final ArrayList locks = new ArrayList(); getAdminClient().setEventHandler(new SVNAdminEventAdapter() { public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.LOCK_LISTED) { SVNLock svnLock = event.getLock(); Lock lock = JavaHLObjectFactory.createLock(svnLock); locks.add(lock); } } }); try { getAdminClient().doListLocks(new File(path).getAbsoluteFile()); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } finally { getAdminClient().setEventHandler(null); } return (Lock[]) locks.toArray(new Lock[locks.size()]); } /** * remove multiple locks from the repository * * @param path the path to the repository * @param locks the name of the locked items * @throws ClientException throw in case of problem * @since 1.2 */ public void rmlocks(String path, String[] locks) throws ClientException { try { getAdminClient().doRemoveLocks(new File(path).getAbsoluteFile(), locks); } catch (SVNException e) { JavaHLObjectFactory.throwException(e, myDelegate); } finally { getAdminClient().setEventHandler(null); } } private static OutputStream createOutputStream(final OutputInterface dataOut) { if (dataOut == null) { return SVNFileUtil.DUMMY_OUT; } return new OutputStream() { public void write(int b) throws IOException { dataOut.write(new byte[]{(byte) (b & 0xFF)}); } public void write(byte[] b) throws IOException { dataOut.write(b); } public void close() throws IOException { dataOut.close(); } public void write(byte[] b, int off, int len) throws IOException { byte[] copy = new byte[len]; System.arraycopy(b, off, copy, 0, len); dataOut.write(copy); } }; } private static InputStream createInputStream(final InputInterface dataIn) { if (dataIn == null) { return SVNFileUtil.DUMMY_IN; } return new InputStream() { public int read() throws IOException { byte[] b = new byte[1]; int r = dataIn.read(b); if (r <= 0) { return -1; } return b[0] & 0xFF; } public void close() throws IOException { dataIn.close(); } public int read(byte[] b, int off, int len) throws IOException { byte[] copy = new byte[len]; int realLen = dataIn.read(copy); if (realLen <= 0) { return realLen; } System.arraycopy(copy, 0, b, off, realLen); return realLen; } public int read(byte[] b) throws IOException { return dataIn.read(b); } }; } private void notImplementedYet() throws ClientException { notImplementedYet(null); } private void notImplementedYet(String message) throws ClientException { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, message == null ? "Requested SVNAdmin functionality is not yet implemented" : message); JavaHLObjectFactory.throwException(new SVNException(err), myDelegate); } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tigris/subversion/javahl/SVNClient.java000066400000000000000000000704051177510526000315630ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tigris.subversion.javahl; import java.io.OutputStream; import java.util.Map; import org.tmatesoft.svn.core.javahl.SVNClientImpl; /** * * @version 1.3 * @author TMate Software Ltd. */ public class SVNClient implements SVNClientInterface { private SVNClientImpl myDelegate; public static final class LogLevel implements SVNClientLogLevel { } public SVNClient() { myDelegate = SVNClientImpl.newInstance(this); } public String getLastPath() { return myDelegate.getLastPath(); } public Status[] status(String path, boolean descend, boolean onServer, boolean getAll) throws ClientException { return myDelegate.status(path, descend, onServer, getAll); } public Status[] status(String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore) throws ClientException { return myDelegate.status(path, descend, onServer, getAll, noIgnore, false); } public Status[] status(final String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals) throws ClientException { return myDelegate.status(path, descend, onServer, getAll, noIgnore, ignoreExternals); } public DirEntry[] list(String url, Revision revision, boolean recurse) throws ClientException { return myDelegate.list(url, revision, recurse); } public DirEntry[] list(String url, Revision revision, Revision pegRevision, boolean recurse) throws ClientException { return myDelegate.list(url, revision, pegRevision, recurse); } public Status singleStatus(final String path, boolean onServer) throws ClientException { return myDelegate.singleStatus(path, onServer); } public void username(String username) { myDelegate.username(username); } public void password(String password) { myDelegate.password(password); } public void setPrompt(PromptUserPassword prompt) { myDelegate.setPrompt(prompt); } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd) throws ClientException { return myDelegate.logMessages(path, revisionStart, revisionEnd); } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy) throws ClientException { return myDelegate.logMessages(path, revisionStart, revisionEnd, stopOnCopy); } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath) throws ClientException { return myDelegate.logMessages(path, revisionStart, revisionEnd, stopOnCopy, discoverPath); } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, long limit) throws ClientException { return myDelegate.logMessages(path, revisionStart, revisionEnd, stopOnCopy, discoverPath, limit); } public long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, boolean recurse, boolean ignoreExternals) throws ClientException { return myDelegate.checkout(moduleName, destPath, revision, pegRevision, recurse, ignoreExternals); } public long checkout(String moduleName, String destPath, Revision revision, boolean recurse) throws ClientException { return myDelegate.checkout(moduleName, destPath, revision, recurse); } /** * @deprecated */ public void notification(Notify notify) { myDelegate.notification(notify); } public void notification2(Notify2 notify) { myDelegate.notification2(notify); } public void commitMessageHandler(CommitMessage messageHandler) { myDelegate.commitMessageHandler(messageHandler); } public void remove(String[] path, String message, boolean force) throws ClientException { myDelegate.remove(path, message, force); } public void remove(String[] path, String message, boolean force, boolean keepLocal, Map revpropTable) throws ClientException { myDelegate.remove(path, message, force, keepLocal, revpropTable); } public void revert(String path, boolean recurse) throws ClientException { myDelegate.revert(path, recurse); } public void add(String path, boolean recurse) throws ClientException { myDelegate.add(path, recurse); } public void add(String path, boolean recurse, boolean force) throws ClientException { myDelegate.add(path, recurse, force); } public long update(String path, Revision revision, boolean recurse) throws ClientException { return myDelegate.update(path, revision, recurse); } public long[] update(String[] path, Revision revision, boolean recurse, boolean ignoreExternals) throws ClientException { return myDelegate.update(path, revision, recurse, ignoreExternals); } public long commit(String[] path, String message, boolean recurse) throws ClientException { return myDelegate.commit(path, message, recurse); } public long commit(String[] path, String message, boolean recurse, boolean noUnlock) throws ClientException { return myDelegate.commit(path, message, recurse, noUnlock); } public void copy(String srcPath, String destPath, String message, Revision revision) throws ClientException { myDelegate.copy(srcPath, destPath, message, revision); } public void move(String srcPath, String destPath, String message, Revision revision, boolean force) throws ClientException { myDelegate.move(srcPath, destPath, message, revision, force); } public void move(String srcPath, String destPath, String message, boolean force) throws ClientException { myDelegate.move(srcPath, destPath, message, force); } public void mkdir(String[] path, String message) throws ClientException { myDelegate.mkdir(path, message); } public void cleanup(String path) throws ClientException { myDelegate.cleanup(path); } public void resolve(String path, int depth, int conflictResult) throws SubversionException { myDelegate.resolve(path, depth, conflictResult); } public void resolved(String path, boolean recurse) throws ClientException { myDelegate.resolved(path, recurse); } public long doExport(String srcPath, String destPath, Revision revision, boolean force) throws ClientException { return myDelegate.doExport(srcPath, destPath, revision, force); } public long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, boolean recurse, String nativeEOL) throws ClientException { return myDelegate.doExport(srcPath, destPath, revision, pegRevision, force, ignoreExternals, recurse, nativeEOL); } public long doSwitch(String path, String url, Revision revision, boolean recurse) throws ClientException { return myDelegate.doSwitch(path, url, revision, recurse); } public void doImport(String path, String url, String message, boolean recurse) throws ClientException { myDelegate.doImport(path, url, message, recurse); } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, boolean recurse) throws ClientException { myDelegate.merge(path1, revision1, path2, revision2, localPath, force, recurse); } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, boolean recurse, boolean ignoreAncestry, boolean dryRun) throws ClientException { myDelegate.merge(path1, revision1, path2, revision2, localPath, force, recurse, ignoreAncestry, dryRun); } public void merge(String path, Revision pegRevision, Revision revision1, Revision revision2, String localPath, boolean force, boolean recurse, boolean ignoreAncestry, boolean dryRun) throws ClientException { myDelegate.merge(path, pegRevision, revision1, revision2, localPath, force, recurse, ignoreAncestry, dryRun); } public void diff(String target1, Revision revision1, String target2, Revision revision2, String outFileName, boolean recurse) throws ClientException { myDelegate.diff(target1, revision1, target2, revision2, outFileName, recurse); } public void diff(String target1, Revision revision1, String target2, Revision revision2, String outFileName, boolean recurse, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { myDelegate.diff(target1, revision1, target2, revision2, outFileName, recurse, ignoreAncestry, noDiffDeleted, force); } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String outFileName, boolean recurse, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { myDelegate.diff(target, pegRevision, startRevision, endRevision, outFileName, recurse, ignoreAncestry, noDiffDeleted, force); } public PropertyData[] properties(String path) throws ClientException { return myDelegate.properties(path); } public PropertyData[] properties(String path, Revision revision) throws ClientException { return myDelegate.properties(path, revision); } public PropertyData[] properties(String path, Revision revision, Revision pegRevision) throws ClientException { return myDelegate.properties(path, revision, pegRevision); } public void propertySet(String path, String name, byte[] value, boolean recurse) throws ClientException { myDelegate.propertySet(path, name, value, recurse); } public void propertySet(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException { myDelegate.propertySet(path, name, value, recurse, force); } public void propertySet(String path, String name, String value, boolean recurse) throws ClientException { myDelegate.propertySet(path, name, value, recurse); } public void propertySet(String path, String name, String value, boolean recurse, boolean force) throws ClientException { myDelegate.propertySet(path, name, value, recurse, force); } public void propertyRemove(String path, String name, boolean recurse) throws ClientException { myDelegate.propertyRemove(path, name, recurse); } public void propertyCreate(String path, String name, String value, boolean recurse) throws ClientException { myDelegate.propertyCreate(path, name, value, recurse); } public void propertyCreate(String path, String name, String value, boolean recurse, boolean force) throws ClientException { myDelegate.propertyCreate(path, name, value, recurse, force); } public void propertyCreate(String path, String name, byte[] value, boolean recurse) throws ClientException { myDelegate.propertyCreate(path, name, value, recurse); } public void propertyCreate(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException { myDelegate.propertyCreate(path, name, value, recurse, force); } public PropertyData revProperty(String path, String name, Revision rev) throws ClientException { return myDelegate.revProperty(path, name, rev); } public PropertyData[] revProperties(String path, Revision rev) throws ClientException { return myDelegate.revProperties(path, rev); } public void setRevProperty(String path, String name, Revision rev, String value, boolean force) throws ClientException { myDelegate.setRevProperty(path, name, rev, value, force); } public PropertyData propertyGet(String path, String name) throws ClientException { return myDelegate.propertyGet(path, name); } public PropertyData propertyGet(String path, String name, Revision revision) throws ClientException { return myDelegate.propertyGet(path, name, revision); } public PropertyData propertyGet(String path, String name, Revision revision, Revision pegRevision) throws ClientException { return myDelegate.propertyGet(path, name, revision, pegRevision); } public byte[] fileContent(String path, Revision revision) throws ClientException { return myDelegate.fileContent(path, revision); } public byte[] fileContent(String path, Revision revision, Revision pegRevision) throws ClientException { return myDelegate.fileContent(path, revision, pegRevision); } public void streamFileContent(String path, Revision revision, Revision pegRevision, int bufferSize, OutputStream stream) throws ClientException { myDelegate.streamFileContent(path, revision, pegRevision, bufferSize, stream); } public void relocate(String from, String to, String path, boolean recurse) throws ClientException { myDelegate.relocate(from, to, path, recurse); } public byte[] blame(String path, Revision revisionStart, Revision revisionEnd) throws ClientException { return myDelegate.blame(path, revisionStart, revisionEnd); } public void blame(String path, Revision revisionStart, Revision revisionEnd, BlameCallback callback) throws ClientException { myDelegate.blame(path, revisionStart, revisionEnd, callback); } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, final BlameCallback callback) throws ClientException { myDelegate.blame(path, pegRevision, revisionStart, revisionEnd, callback); } public void dispose() { myDelegate.dispose(); } public void setConfigDirectory(String configDir) throws ClientException { myDelegate.setConfigDirectory(configDir); } public String getConfigDirectory() throws ClientException { return myDelegate.getConfigDirectory(); } public void cancelOperation() throws ClientException { myDelegate.cancelOperation(); } public Info info(String path) throws ClientException { return myDelegate.info(path); } public void lock(String[] path, String comment, boolean force) throws ClientException { myDelegate.lock(path, comment, force); } public void unlock(String[] path, boolean force) throws ClientException { myDelegate.unlock(path, force); } public Info2[] info2(String pathOrUrl, Revision revision, Revision pegRevision, boolean recurse) throws ClientException { return myDelegate.info2(pathOrUrl, revision, pegRevision, recurse); } public String getVersionInfo(String path, String trailUrl, boolean lastChanged) throws ClientException { return myDelegate.getVersionInfo(path, trailUrl, lastChanged); } public String getAdminDirectoryName() { return myDelegate.getAdminDirectoryName(); } public boolean isAdminDirectory(String name) { return myDelegate.isAdminDirectory(name); } public static String version() { return SVNClientImpl.version(); } public static int versionMajor() { return SVNClientImpl.versionMajor(); } public static int versionMinor() { return SVNClientImpl.versionMinor(); } public static int versionMicro() { return SVNClientImpl.versionMicro(); } public static long versionRevisionNumber() { return SVNClientImpl.versionRevisionNumber(); } public static void enableLogging(int logLevel, String logFilePath) { SVNClientImpl.enableLogging(logLevel, logFilePath); } public Version getVersion() { return myDelegate.getVersion(); } public static void initNative() { } public void setProgressListener(ProgressListener listener) { myDelegate.setProgressListener(listener); } public void getChangelists(String rootPath, String[] changelists, int depth, ChangelistCallback callback) throws ClientException { myDelegate.getChangelists(rootPath, changelists, depth, callback); } public long commit(String[] path, String message, int depth, boolean noUnlock, boolean keepChangelist, String[] changelists, Map revpropTable) throws ClientException { return myDelegate.commit(path, message, depth, noUnlock, keepChangelist, changelists, revpropTable); } public void remove(String[] path, String message, boolean force, boolean keepLocal) throws ClientException { remove(path, message, force, keepLocal, null); } public long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, int depth, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { return myDelegate.checkout(moduleName, destPath, revision, pegRevision, depth, ignoreExternals, allowUnverObstructions); } public long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, int depth, String nativeEOL) throws ClientException { return myDelegate.doExport(srcPath, destPath, revision, pegRevision, force, ignoreExternals, depth, nativeEOL); } public void getMergeinfoLog(int kind, String pathOrUrl, Revision pegRevision, String mergeSourceUrl, Revision srcPegRevision, boolean discoverChangedPaths, String[] revprops, LogMessageCallback callback) throws ClientException { myDelegate.getMergeinfoLog(kind, pathOrUrl, pegRevision, mergeSourceUrl, srcPegRevision, discoverChangedPaths, revprops, callback); } public long update(String path, Revision revision, int depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { return myDelegate.update(path, revision, depth, depthIsSticky, ignoreExternals, allowUnverObstructions); } public long[] update(String[] path, Revision revision, int depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { return myDelegate.update(path, revision, depth, depthIsSticky, ignoreExternals, allowUnverObstructions); } public void status(String path, int depth, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals, String[] changelists, StatusCallback callback) throws ClientException { myDelegate.status(path, depth, onServer, getAll, noIgnore, ignoreExternals, changelists, callback); } public void list(String url, Revision revision, Revision pegRevision, int depth, int direntFields, boolean fetchLocks, ListCallback callback) throws ClientException { myDelegate.list(url, revision, pegRevision, depth, direntFields, fetchLocks, callback); } public void mkdir(String[] path, String message, boolean makeParents, Map revpropTable) throws ClientException { myDelegate.mkdir(path, message, makeParents, revpropTable); } public void setConflictResolver(ConflictResolverCallback listener) { myDelegate.setConflictResolver(listener); } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, BlameCallback2 callback) throws ClientException { myDelegate.blame(path, pegRevision, revisionStart, revisionEnd, ignoreMimeType, includeMergedRevisions, callback); } public String[] suggestMergeSources(String path, Revision pegRevision) throws SubversionException { return myDelegate.suggestMergeSources(path, pegRevision); } public void copy(CopySource[] sources, String destPath, String message, boolean copyAsChild, boolean makeParents, Map revpropTable) throws ClientException { myDelegate.copy(sources, destPath, message, copyAsChild, makeParents, revpropTable); } public void move(String[] srcPaths, String destPath, String message, boolean force, boolean moveAsChild, boolean makeParents, Map revpropTable) throws ClientException { myDelegate.move(srcPaths, destPath, message, force, moveAsChild, makeParents, revpropTable); } public void add(String path, int depth, boolean force, boolean noIgnores, boolean addParents) throws ClientException { myDelegate.add(path, depth, force, noIgnores, addParents); } public void doImport(String path, String url, String message, int depth, boolean noIgnore, boolean ignoreUnknownNodeTypes, Map revpropTable) throws ClientException { myDelegate.doImport(path, url, message, depth, noIgnore, ignoreUnknownNodeTypes, revpropTable); } public long doSwitch(String path, String url, Revision revision, Revision pegRevision, int depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { return myDelegate.doSwitch(path, url, revision, pegRevision, depth, depthIsSticky, ignoreExternals, allowUnverObstructions); } public void logMessages(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, boolean includeMergedRevisions, String[] revProps, long limit, LogMessageCallback callback) throws ClientException { myDelegate.logMessages(path, pegRevision, revisionStart, revisionEnd, stopOnCopy, discoverPath, includeMergedRevisions, revProps, limit, callback); } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, int depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { myDelegate.merge(path1, revision1, path2, revision2, localPath, force, depth, ignoreAncestry, dryRun, recordOnly); } public void merge(String path, Revision pegRevision, RevisionRange[] revisions, String localPath, boolean force, int depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { myDelegate.merge(path, pegRevision, revisions, localPath, force, depth, ignoreAncestry, dryRun, recordOnly); } public void mergeReintegrate(String path, Revision pegRevision, String localPath, boolean dryRun) throws ClientException { myDelegate.mergeReintegrate(path, pegRevision, localPath, dryRun); } public void info2(String pathOrUrl, Revision revision, Revision pegRevision, int depth, String[] changelists, InfoCallback callback) throws ClientException { myDelegate.info2(pathOrUrl, revision, pegRevision, depth, changelists, callback); } public void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { myDelegate.diff(target1, revision1, target2, revision2, relativeToDir, outFileName, depth, changelists, ignoreAncestry, noDiffDeleted, force); } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { myDelegate.diff(target, pegRevision, startRevision, endRevision, relativeToDir, outFileName, depth, changelists, ignoreAncestry, noDiffDeleted, force); } public void diffSummarize(String target1, Revision revision1, String target2, Revision revision2, int depth, String[] changelists, boolean ignoreAncestry, DiffSummaryReceiver receiver) throws ClientException { myDelegate.diffSummarize(target1, revision1, target2, revision2, depth, changelists, ignoreAncestry, receiver); } public void diffSummarize(String target, Revision pegRevision, Revision startRevision, Revision endRevision, int depth, String[] changelists, boolean ignoreAncestry, DiffSummaryReceiver receiver) throws ClientException { myDelegate.diffSummarize(target, pegRevision, startRevision, endRevision, depth, changelists, ignoreAncestry, receiver); } public void addToChangelist(String[] paths, String changelist, int depth, String[] changelists) throws ClientException { myDelegate.addToChangelist(paths, changelist, depth, changelists); } public void removeFromChangelists(String[] paths, int depth, String[] changelist) throws ClientException { myDelegate.removeFromChangelists(paths, depth, changelist); } public void properties(String path, Revision revision, Revision pegRevision, int depth, String[] changelists, ProplistCallback callback) throws ClientException { myDelegate.properties(path, revision, pegRevision, depth, changelists, callback); } public void propertyCreate(String path, String name, String value, int depth, String[] changelists, boolean force) throws ClientException { myDelegate.propertyCreate(path, name, value, depth, changelists, force); } public void propertyRemove(String path, String name, int depth, String[] changelists) throws ClientException { myDelegate.propertyRemove(path, name, depth, changelists); } public void propertySet(String path, String name, String value, int depth, String[] changelists, boolean force, Map revpropTable) throws ClientException { myDelegate.propertySet(path, name, value, depth, changelists, force, revpropTable); } public void revert(String path, int depth, String[] changelists) throws ClientException { myDelegate.revert(path, depth, changelists); } public Mergeinfo getMergeinfo(String path, Revision pegRevision) throws SubversionException { return myDelegate.getMergeinfo(path, pegRevision); } public void logMessages(String path, Revision pegRevision, RevisionRange[] ranges, boolean stopOnCopy, boolean discoverPath, boolean includeMergedRevisions, String[] revProps, long limit, LogMessageCallback callback) throws ClientException { myDelegate.logMessages(path, pegRevision, ranges, stopOnCopy, discoverPath, includeMergedRevisions, revProps, limit, callback); } public void setRevProperty(String path, String name, Revision rev, String value, String originalValue, boolean force) throws ClientException { myDelegate.setRevProperty(path, name, rev, value, originalValue, force); } public void copy(CopySource[] sources, String destPath, String message, boolean copyAsChild, boolean makeParents, boolean ignoreExternals, Map revpropTable) throws ClientException { // TODO Auto-generated method stub } public void getMergeinfoLog(int kind, String pathOrUrl, Revision pegRevision, String mergeSourceUrl, Revision srcPegRevision, boolean discoverChangedPaths, int depth, String[] revProps, LogMessageCallback callback) throws ClientException { // TODO Auto-generated method stub } public void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { // TODO Auto-generated method stub } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { // TODO Auto-generated method stub } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, BlameCallback3 callback) throws ClientException { // TODO Auto-generated method stub } public void upgrade(String path) throws ClientException { // TODO Auto-generated method stub } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/000077500000000000000000000000001177510526000241465ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/000077500000000000000000000000001177510526000247545ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/000077500000000000000000000000001177510526000257045ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/000077500000000000000000000000001177510526000271515ustar00rootroot00000000000000JavaHLAuthenticationProvider.java000066400000000000000000000261421177510526000354620ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.io.File; import java.security.cert.X509Certificate; import java.text.MessageFormat; import org.tigris.subversion.javahl.PromptUserPassword; import org.tigris.subversion.javahl.PromptUserPassword2; import org.tigris.subversion.javahl.PromptUserPassword3; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.auth.SVNSSHAuthentication; import org.tmatesoft.svn.core.auth.SVNSSLAuthentication; import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication; import org.tmatesoft.svn.core.internal.util.SVNSSLUtil; import org.tmatesoft.svn.core.internal.wc.ISVNSSLPasspharsePromptSupport; /** * @version 1.3 * @author TMate Software Ltd. */ class JavaHLAuthenticationProvider implements ISVNAuthenticationProvider, ISVNSSLPasspharsePromptSupport { private static final String ADAPTER_DEFAULT_PROMPT_CLASS = "org.tigris.subversion.svnclientadapter.javahl.AbstractJhlClientAdapter$DefaultPromptUserPassword"; private PromptUserPassword myPrompt; public JavaHLAuthenticationProvider(PromptUserPassword prompt){ myPrompt = prompt; } public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) { if (ISVNAuthenticationManager.SSH.equals(kind) && myPrompt instanceof PromptUserPasswordSSH) { PromptUserPasswordSSH prompt4 = (PromptUserPasswordSSH) myPrompt; String userName = previousAuth != null && previousAuth.getUserName() != null ? previousAuth.getUserName() : getUserName(null, url); int port = url != null ? url.getPort() : -1; if (prompt4.promptSSH(realm, userName, port, authMayBeStored)) { String password = prompt4.getPassword(); String keyPath = prompt4.getSSHPrivateKeyPath(); String passphrase = prompt4.getSSHPrivateKeyPassphrase(); userName = getUserName(prompt4.getUsername(), url); if ("".equals(passphrase)) { passphrase = null; } port = prompt4.getSSHPort(); if (port < 0 && url != null) { port = url.getPort(); } if (port < 0) { port = 22; } boolean save = prompt4.userAllowedSave(); if (keyPath != null && !"".equals(keyPath)) { return new SVNSSHAuthentication(userName, new File(keyPath), passphrase, port, save, url, false); } else if (password != null){ return new SVNSSHAuthentication(userName, password, port, save, url, false); } } return null; } else if (ISVNAuthenticationManager.SSL.equals(kind) && SVNSSLAuthentication.isCertificatePath(realm) && myPrompt instanceof PromptUserPassword3) { String passphrase = ((PromptUserPassword3) myPrompt).askQuestion(realm, "SSL Certificate Passphrase", authMayBeStored); if (passphrase != null) { return new SVNPasswordAuthentication("", passphrase, ((PromptUserPassword3) myPrompt).userAllowedSave(), url, false); } } else if (ISVNAuthenticationManager.SSL.equals(kind) && !SVNSSLAuthentication.isCertificatePath(realm) && myPrompt instanceof PromptUserPasswordSSL) { PromptUserPasswordSSL prompt4 = (PromptUserPasswordSSL) myPrompt; if (prompt4.promptSSL(realm, authMayBeStored)) { String cert = prompt4.getSSLClientCertPath(); String password = prompt4.getSSLClientCertPassword(); if (cert != null) { if ("".equals(password)) { password = null; } boolean save = prompt4.userAllowedSave(); if (cert.startsWith(SVNSSLAuthentication.MSCAPI)) { String alias = null; if (cert.lastIndexOf(';') > 0) { alias = cert.substring(cert.lastIndexOf(';') + 1); } return new SVNSSLAuthentication(SVNSSLAuthentication.MSCAPI, alias, save, url, false); } SVNSSLAuthentication sslAuth = new SVNSSLAuthentication(new File(cert), password, save, url, false); sslAuth.setCertificatePath(cert); return sslAuth; } } return null; } if (ISVNAuthenticationManager.SSH.equals(kind) && previousAuth == null) { // use configuration file here? but it was already used once... String keyPath = System.getProperty("svnkit.ssh2.key", System.getProperty("javasvn.ssh2.key")); String userName = getUserName(System.getProperty("svnkit.ssh2.username", System.getProperty("javasvn.ssh2.username")), url); String passPhrase = System.getProperty("svnkit.ssh2.passphrase", System.getProperty("javasvn.ssh2.passphrase")); if (userName == null) { return null; } if (keyPath != null && previousAuth == null) { // use port number from configuration file? return new SVNSSHAuthentication(userName, new File(keyPath), passPhrase, -1, true, url, false); } // try to get password for ssh from the user. } else if(ISVNAuthenticationManager.USERNAME.equals(kind)) { String userName = previousAuth != null && previousAuth.getUserName() != null ? previousAuth.getUserName() : getUserName(null, url); if (myPrompt instanceof PromptUserPasswordUser) { PromptUserPasswordUser prompt3 = (PromptUserPasswordUser) myPrompt; if (prompt3.promptUser(realm, userName, authMayBeStored)) { return new SVNUserNameAuthentication(prompt3.getUsername(), prompt3.userAllowedSave(), url, false); } return getDefaultUserNameCredentials(userName); } else if (myPrompt instanceof PromptUserPassword3) { PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt; if (prompt3.prompt(realm, userName, authMayBeStored)) { return new SVNUserNameAuthentication(prompt3.getUsername(), prompt3.userAllowedSave(), url, false); } return getDefaultUserNameCredentials(userName); } if (myPrompt.prompt(realm, userName)) { return new SVNUserNameAuthentication(myPrompt.getUsername(), false, url, false); } return getDefaultUserNameCredentials(userName); } else if(!ISVNAuthenticationManager.PASSWORD.equals(kind)){ return null; } String userName = previousAuth != null && previousAuth.getUserName() != null ? previousAuth.getUserName() : getUserName(null, url); if (myPrompt instanceof PromptUserPassword3) { PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt; if(prompt3.prompt(realm, userName, authMayBeStored)){ if (ISVNAuthenticationManager.SSH.equals(kind)) { // use default port number from configuration file (should be in previous auth). int portNumber = (previousAuth instanceof SVNSSHAuthentication) ? ((SVNSSHAuthentication) previousAuth).getPortNumber() : -1; return new SVNSSHAuthentication(prompt3.getUsername(), prompt3.getPassword(), portNumber, prompt3.userAllowedSave(), url, false); } return new SVNPasswordAuthentication(prompt3.getUsername(), prompt3.getPassword(), prompt3.userAllowedSave(), url, false); } }else{ if(myPrompt.prompt(realm, userName)){ if (ISVNAuthenticationManager.SSH.equals(kind)) { return new SVNSSHAuthentication(userName, myPrompt.getPassword(), -1, true, url, false); } return new SVNPasswordAuthentication(myPrompt.getUsername(), myPrompt.getPassword(), true, url, false); } } return null; } private SVNAuthentication getDefaultUserNameCredentials(String userName) { if (ADAPTER_DEFAULT_PROMPT_CLASS.equals(myPrompt.getClass().getName())) { // return default username, despite prompt was 'cancelled'. return new SVNUserNameAuthentication(userName, false, null, false); } return null; } public int acceptServerAuthentication(SVNURL url, String realm, Object serverAuth, boolean resultMayBeStored) { if (myPrompt instanceof PromptUserPassword2 && serverAuth instanceof X509Certificate) { PromptUserPassword2 sslPrompt = (PromptUserPassword2) myPrompt; serverAuth = serverAuth instanceof X509Certificate ? SVNSSLUtil.getServerCertificatePrompt((X509Certificate) serverAuth, realm, url.getHost()) : serverAuth; if (serverAuth == null) { serverAuth = "Unsupported certificate type '" + (serverAuth != null ? serverAuth.getClass().getName() : "null") + "'"; } return sslPrompt.askTrustSSLServer(serverAuth.toString(), resultMayBeStored); } else if (myPrompt != null && serverAuth instanceof byte[]) { String prompt = "The ''{0}'' server''s key fingerprint is:\n{1}\n" + "If you trust this host, select ''Yes'' to add the key to the SVN cache and carry on connecting.\n" + "If you do not trust this host, select ''No'' to abandon the connection."; prompt = MessageFormat.format(prompt, new Object[] {url.getHost(), SVNSSLUtil.getFingerprint((byte[]) serverAuth, "MD5")}); if (!myPrompt.askYesNo(realm, prompt, false)) { return REJECTED; } } return ACCEPTED; } public boolean isSSLPassphrasePromtSupported() { return true; } private static String getUserName(String userName, SVNURL url) { if (userName == null || "".equals(userName.trim())) { userName = url != null ? url.getUserInfo() : null; } if (userName == null || "".equals(userName.trim())) { userName = System.getProperty("user.name"); } return userName; } } JavaHLAuthenticationStorage.java000066400000000000000000000022241177510526000352670ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.util.Hashtable; import java.util.Map; import org.tmatesoft.svn.core.internal.wc.ISVNAuthenticationStorage; /** * @version 1.3 * @author TMate Software Ltd. */ public class JavaHLAuthenticationStorage implements ISVNAuthenticationStorage { private Map myStorage = new Hashtable(); public void putData(String kind, String realm, Object data) { myStorage.put(kind + "$" + realm, data); } public Object getData(String kind, String realm) { return myStorage.get(kind + "$" + realm); } public void clear() { myStorage.clear(); } } JavaHLCompositeLog.java000066400000000000000000000063551177510526000334000ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.util.ISVNDebugLog; import org.tmatesoft.svn.util.SVNDebugLogAdapter; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class JavaHLCompositeLog extends SVNDebugLogAdapter { Map myLoggers; public JavaHLCompositeLog() { myLoggers = new HashMap(); } public void addLogger(ISVNDebugLog debugLog) { Boolean needTracing = checkTracing(debugLog); myLoggers.put(debugLog, needTracing); } public void removeLogger(ISVNDebugLog debugLog) { myLoggers.remove(debugLog); } private static Boolean checkTracing(ISVNDebugLog log) { InputStream is = log.createLogStream(SVNLogType.NETWORK, SVNFileUtil.DUMMY_IN); OutputStream os = log.createLogStream(SVNLogType.NETWORK, SVNFileUtil.DUMMY_OUT); if (is == SVNFileUtil.DUMMY_IN && os == SVNFileUtil.DUMMY_OUT) { return Boolean.FALSE; } return Boolean.TRUE; } public InputStream createLogStream(SVNLogType logType, InputStream is) { if (myLoggers.containsValue(Boolean.TRUE)) { return super.createLogStream(logType, is); } return is; } public OutputStream createLogStream(SVNLogType logType, OutputStream os) { if (myLoggers.containsValue(Boolean.TRUE)) { return super.createLogStream(logType, os); } return os; } public void log(SVNLogType logType, String message, byte[] data) { for (Iterator iterator = myLoggers.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); ISVNDebugLog log = (ISVNDebugLog) entry.getKey(); Boolean needTracing = (Boolean) entry.getValue(); if (needTracing.booleanValue()) { log.log(logType, message, data); } } } public void log(SVNLogType logType, Throwable th, Level logLevel) { for (Iterator iterator = myLoggers.keySet().iterator(); iterator.hasNext();) { ISVNDebugLog log = (ISVNDebugLog) iterator.next(); log.log(logType, th, logLevel); } } public void log(SVNLogType logType, String message, Level logLevel) { for (Iterator iterator = myLoggers.keySet().iterator(); iterator.hasNext();) { ISVNDebugLog log = (ISVNDebugLog) iterator.next(); log.log(logType, message, logLevel); } } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/JavaHLDebugLog.java000066400000000000000000000106341177510526000325360ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.util.SVNDebugLogAdapter; import org.tmatesoft.svn.util.SVNLogType; import org.tigris.subversion.javahl.JavaHLObjectFactory; import org.tigris.subversion.javahl.SVNClientLogLevel; /** * @author TMate Software Ltd. * @version 1.3 */ public class JavaHLDebugLog extends SVNDebugLogAdapter { private static final String JAVAHL_LOGGER_NAME = "svnkit-javahl"; private static JavaHLDebugLog ourInstance = new JavaHLDebugLog(); private Map myHandlers = new HashMap(); private Logger myLogger; public static JavaHLDebugLog getInstance() { return ourInstance; } public synchronized void enableLogging(int logLevel, File logPath, Formatter formatter) throws SVNException { logPath = logPath.getAbsoluteFile(); if (logLevel == SVNClientLogLevel.NoLog) { if (logPath == null) { resetLogHandlers(); } else { Handler handler = (Handler) myHandlers.remove(logPath); if (handler != null) { handler.close(); getLogger().removeHandler(handler); } } return; } Level level = JavaHLObjectFactory.getLoggingLevel(logLevel); Handler handler = (Handler) myHandlers.get(logPath); if (handler == null) { try { handler = new FileHandler(logPath.getAbsolutePath(), true); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getMessage()), e, SVNLogType.DEFAULT); } myHandlers.put(logPath, handler); } handler.setFormatter(formatter); handler.setLevel(level); getLogger().addHandler(handler); } private void resetLogHandlers() { if (getLogger().getHandlers() == null) { return; } for (int i = 0; i < getLogger().getHandlers().length; i++) { Handler handler = getLogger().getHandlers()[i]; handler.close(); getLogger().removeHandler(handler); } } private Logger getLogger() { if (myLogger == null) { myLogger = Logger.getLogger(JAVAHL_LOGGER_NAME); myLogger.setUseParentHandlers(false); myLogger.setLevel(Level.ALL); resetLogHandlers(); } return myLogger; } public void log(SVNLogType logType, String message, byte[] data) { if (getLogger().isLoggable(Level.FINEST)) { try { getLogger().log(Level.FINEST, getMessage(message + "\n" + new String(data, "UTF-8"))); } catch (UnsupportedEncodingException e) { getLogger().log(Level.FINEST, getMessage(message + "\n" + new String(data))); } } } public void log(SVNLogType logType, Throwable th, Level logLevel) { if (getLogger().isLoggable(logLevel) && th != null) { getLogger().log(logLevel, getMessage(th.getMessage()), th); } } public void log(SVNLogType logType, String message, Level logLevel) { if (getLogger().isLoggable(logLevel) && message != null) { getLogger().log(logLevel, getMessage(message)); } } private String getMessage(String originalMessage) { return "JAVAHL" + ": " + originalMessage; } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/JavaHLProgressLog.java000066400000000000000000000031671177510526000333170ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.util.logging.Level; import org.tigris.subversion.javahl.JavaHLObjectFactory; import org.tigris.subversion.javahl.ProgressEvent; import org.tigris.subversion.javahl.ProgressListener; import org.tmatesoft.svn.util.SVNDebugLogAdapter; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class JavaHLProgressLog extends SVNDebugLogAdapter { private ProgressListener myProgressListener; private long myProgress; public JavaHLProgressLog(ProgressListener progressListener) { myProgressListener = progressListener; reset(); } public void log(SVNLogType logType, String message, byte[] data) { myProgress += data.length; ProgressEvent event = JavaHLObjectFactory.createProgressEvent(myProgress, -1L); myProgressListener.onProgress(event); } public void reset() { myProgress = 0; } public void log(SVNLogType logType, Throwable th, Level logLevel) { } public void log(SVNLogType logType, String message, Level logLevel) { } } JavaHLPropertyHandler.java000066400000000000000000000045471177510526000341170ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.io.File; import java.util.ArrayList; import java.util.Collection; import org.tigris.subversion.javahl.JavaHLObjectFactory; import org.tigris.subversion.javahl.PropertyData; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.ISVNPropertyHandler; import org.tmatesoft.svn.core.wc.SVNPropertyData; /** * @version 1.3 * @author TMate Software Ltd. */ class JavaHLPropertyHandler implements ISVNPropertyHandler{ private PropertyData myData = null; private Object myOwner; private Collection myAllData; public JavaHLPropertyHandler(Object owner){ myOwner = owner; myAllData = new ArrayList(); } public void handleProperty(File path, SVNPropertyData property) throws SVNException { myData = JavaHLObjectFactory.createPropertyData(myOwner, path.getAbsolutePath(), property.getName(), property.getValue()); myAllData.add(myData); } public void handleProperty(SVNURL url, SVNPropertyData property) throws SVNException { myData = JavaHLObjectFactory.createPropertyData(myOwner, url.toString(), property.getName(),property.getValue()); myAllData.add(myData); } public void handleProperty(long revision, SVNPropertyData property) throws SVNException { myData = JavaHLObjectFactory.createPropertyData(myOwner, null, property.getName(), property.getValue()); myAllData.add(myData); } public PropertyData getPropertyData(){ if(myData == null){ return null; } if(myData.getValue() == null){ return null; } return myData; } public PropertyData[] getAllPropertyData() { return (PropertyData[]) myAllData.toArray(new PropertyData[myAllData.size()]); } }PromptUserPassword4.java000066400000000000000000000012721177510526000336660ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; /** * @version 1.3 * @author TMate Software Ltd. */ public interface PromptUserPassword4 extends PromptUserPasswordSSH { } PromptUserPasswordSSH.java000066400000000000000000000017161177510526000341630ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import org.tigris.subversion.javahl.PromptUserPassword3; /** * @version 1.3 * @author TMate Software Ltd. */ public interface PromptUserPasswordSSH extends PromptUserPassword3 { public boolean promptSSH(String realm, String username, int sshPort, boolean maySave); public String getSSHPrivateKeyPath(); public String getSSHPrivateKeyPassphrase(); public int getSSHPort(); } PromptUserPasswordSSL.java000066400000000000000000000016231177510526000341640ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import org.tigris.subversion.javahl.PromptUserPassword3; /** * @version 1.3 * @author TMate Software Ltd. */ public interface PromptUserPasswordSSL extends PromptUserPassword3 { public boolean promptSSL(String realm, boolean maySave); public String getSSLClientCertPath(); public String getSSLClientCertPassword(); } PromptUserPasswordUser.java000066400000000000000000000015141177510526000344400ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import org.tigris.subversion.javahl.PromptUserPassword3; /** * @version 1.3 * @author TMate Software Ltd. */ public interface PromptUserPasswordUser extends PromptUserPassword3 { public boolean promptUser(String realm, String defaultUsetName, boolean maySave); } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/SVNClientImpl.java000066400000000000000000003147331177510526000324560ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tigris.subversion.javahl.BlameCallback; import org.tigris.subversion.javahl.BlameCallback2; import org.tigris.subversion.javahl.BlameCallback3; import org.tigris.subversion.javahl.ChangelistCallback; import org.tigris.subversion.javahl.ClientException; import org.tigris.subversion.javahl.CommitItem; import org.tigris.subversion.javahl.CommitMessage; import org.tigris.subversion.javahl.ConflictDescriptor; import org.tigris.subversion.javahl.ConflictResolverCallback; import org.tigris.subversion.javahl.ConflictResult; import org.tigris.subversion.javahl.CopySource; import org.tigris.subversion.javahl.DiffSummaryReceiver; import org.tigris.subversion.javahl.DirEntry; import org.tigris.subversion.javahl.Info; import org.tigris.subversion.javahl.Info2; import org.tigris.subversion.javahl.InfoCallback; import org.tigris.subversion.javahl.JavaHLObjectFactory; import org.tigris.subversion.javahl.ListCallback; import org.tigris.subversion.javahl.LogMessage; import org.tigris.subversion.javahl.LogMessageCallback; import org.tigris.subversion.javahl.Mergeinfo; import org.tigris.subversion.javahl.MergeinfoLogKind; import org.tigris.subversion.javahl.Notify; import org.tigris.subversion.javahl.Notify2; import org.tigris.subversion.javahl.NotifyInformation; import org.tigris.subversion.javahl.ProgressListener; import org.tigris.subversion.javahl.PromptUserPassword; import org.tigris.subversion.javahl.PropertyData; import org.tigris.subversion.javahl.ProplistCallback; import org.tigris.subversion.javahl.Revision; import org.tigris.subversion.javahl.RevisionKind; import org.tigris.subversion.javahl.RevisionRange; import org.tigris.subversion.javahl.SVNClient; import org.tigris.subversion.javahl.SVNClientInterface; import org.tigris.subversion.javahl.SVNClientLogLevel; import org.tigris.subversion.javahl.Status; import org.tigris.subversion.javahl.StatusCallback; import org.tigris.subversion.javahl.SubversionException; import org.tmatesoft.svn.core.ISVNDirEntryHandler; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory; import org.tmatesoft.svn.core.internal.io.dav.http.IHTTPConnectionFactory; import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory; import org.tmatesoft.svn.core.internal.io.svn.ISVNConnectorFactory; import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl; import org.tmatesoft.svn.core.internal.io.svn.SVNSSHConnector; import org.tmatesoft.svn.core.internal.util.DefaultSVNDebugFormatter; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.ISVNAuthenticationStorage; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.wc.DefaultSVNRepositoryPool; import org.tmatesoft.svn.core.wc.ISVNAnnotateHandler; import org.tmatesoft.svn.core.wc.ISVNChangelistHandler; import org.tmatesoft.svn.core.wc.ISVNCommitHandler; import org.tmatesoft.svn.core.wc.ISVNConflictHandler; import org.tmatesoft.svn.core.wc.ISVNDiffStatusHandler; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.ISVNInfoHandler; import org.tmatesoft.svn.core.wc.ISVNOptions; import org.tmatesoft.svn.core.wc.ISVNPropertyHandler; import org.tmatesoft.svn.core.wc.ISVNStatusHandler; import org.tmatesoft.svn.core.wc.SVNChangelistClient; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNCommitClient; import org.tmatesoft.svn.core.wc.SVNCommitItem; import org.tmatesoft.svn.core.wc.SVNCommitPacket; import org.tmatesoft.svn.core.wc.SVNConflictDescription; import org.tmatesoft.svn.core.wc.SVNConflictResult; import org.tmatesoft.svn.core.wc.SVNCopyClient; import org.tmatesoft.svn.core.wc.SVNCopySource; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.core.wc.SVNDiffStatus; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc.SVNInfo; import org.tmatesoft.svn.core.wc.SVNLogClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNRevisionRange; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusClient; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNUpdateClient; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.util.ISVNDebugLog; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; import org.tmatesoft.svn.util.Version; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNClientImpl implements SVNClientInterface { private static int ourInstanceCount; private String myConfigDir; private PromptUserPassword myPrompt; private String myUserName; private String myPassword; private ISVNEventHandler mySVNEventListener; private ISVNConflictHandler mySVNConflictHandler; /** * @deprecated */ private Notify myNotify; private Notify2 myNotify2; private ConflictResolverCallback myConflictResolverCallback; private CommitMessage myMessageHandler; private DefaultSVNOptions myOptions; private boolean myCancelOperation = false; private SVNClientManager myClientManager; private SVNClientInterface myOwner; private JavaHLCompositeLog myDebugLog; private JavaHLProgressLog myProgressListener; private ISVNAuthenticationManager myAuthenticationManager; private ISVNAuthenticationStorage myAuthStorage; private static ISVNAuthenticationStorage ourAuthStorage; /** * @author TMate Software Ltd. * @version 1.3 */ public static final class LogLevel implements SVNClientLogLevel { } public static SVNClientImpl newInstance() { return newInstance(null); } public static SVNClientImpl newInstance(SVNClient owner) { return newInstance(owner, null, null); } public static SVNClientImpl newInstance(SVNClient owner, IHTTPConnectionFactory httpConnectionFactory, ISVNConnectorFactory svnConnectorFactory) { return newInstance(owner, httpConnectionFactory, svnConnectorFactory, true); } public static SVNClientImpl newInstance(SVNClient owner, IHTTPConnectionFactory httpConnectionFactory, ISVNConnectorFactory svnConnectorFactory, boolean trackClient) { SVNClientImpl client = new SVNClientImpl(owner, httpConnectionFactory, svnConnectorFactory); if (trackClient) { SVNClientImplTracker.registerClient(client); } return client; } protected SVNClientImpl(SVNClient owner) { this(owner, null, null); } protected SVNClientImpl(SVNClient owner, IHTTPConnectionFactory httpConnectionFactory, ISVNConnectorFactory svnConnectorFactory) { DAVRepositoryFactory.setup(httpConnectionFactory); SVNRepositoryFactoryImpl.setup(svnConnectorFactory); FSRepositoryFactory.setup(); myConfigDir = SVNWCUtil.getDefaultConfigurationDirectory().getAbsolutePath(); myOwner = owner == null ? (SVNClientInterface) this : (SVNClientInterface) owner; synchronized (SVNClientImpl.class) { ourInstanceCount++; } } public static ISVNAuthenticationStorage getRuntimeCredentialsStorage() { synchronized (SVNClientImpl.class) { if (ourAuthStorage == null) { ourAuthStorage = new JavaHLAuthenticationStorage(); } return ourAuthStorage; } } public static void setRuntimeCredentialsStorage(ISVNAuthenticationStorage storage) { synchronized (SVNClientImpl.class) { ourAuthStorage = storage == null ? new JavaHLAuthenticationStorage() : storage; } } public ISVNAuthenticationStorage getClientCredentialsStorage() { if (myAuthStorage != null) { return myAuthStorage; } return getRuntimeCredentialsStorage(); } public void setClientCredentialsStorage(ISVNAuthenticationStorage storage) { myAuthStorage = storage; updateClientManager(); } public ISVNDebugLog getDebugLog() { if (myDebugLog == null) { myDebugLog = new JavaHLCompositeLog(); myDebugLog.addLogger(SVNDebugLog.getDefaultLog()); myDebugLog.addLogger(JavaHLDebugLog.getInstance()); } return myDebugLog; } public String getLastPath() { return null; } public Status[] status(String path, boolean descend, boolean onServer, boolean getAll) throws ClientException { return status(path, descend, onServer, getAll, false); } public Status[] status(String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore) throws ClientException { return status(path, descend, onServer, getAll, noIgnore, false); } public Status[] status(final String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals) throws ClientException { if (path == null) { return null; } final Collection statuses = new ArrayList(); status(path, JavaHLObjectFactory.unknownOrImmediates(descend), onServer, getAll, noIgnore, ignoreExternals, null, new ISVNStatusHandler() { public void handleStatus(SVNStatus status) { statuses.add(JavaHLObjectFactory.createStatus(status.getFile().getPath(), status)); } }); return (Status[]) statuses.toArray(new Status[statuses.size()]); } public void status(String path, int depth, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals, String[] changelists, StatusCallback callback) throws ClientException { final StatusCallback statusCallback = callback; status(path, depth, onServer, getAll, noIgnore, ignoreExternals, changelists, new ISVNStatusHandler() { public void handleStatus(SVNStatus status) { if (statusCallback != null) { statusCallback.doStatus(JavaHLObjectFactory.createStatus(status.getFile().getPath(), status)); } } }); } private void status(String path, int depth, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals, String[] changelists, ISVNStatusHandler handler) throws ClientException { if (path == null) { return; } SVNStatusClient stClient = getSVNStatusClient(); boolean oldIgnoreExternals = stClient.isIgnoreExternals(); stClient.setIgnoreExternals(ignoreExternals); try { stClient.doStatus(new File(path).getAbsoluteFile(), SVNRevision.HEAD, JavaHLObjectFactory.getSVNDepth(depth), onServer, getAll, noIgnore, !ignoreExternals, handler, JavaHLObjectFactory.getChangeListsCollection(changelists)); } catch (SVNException e) { throwException(e); } finally { stClient.setIgnoreExternals(oldIgnoreExternals); resetLog(); } } public Status singleStatus(final String path, boolean onServer) throws ClientException { Status[] result = status(path, false, onServer, true, false, false); if (result != null && result.length > 0){ return result[0]; } return null; } public DirEntry[] list(String url, Revision revision, boolean recurse) throws ClientException { return list(url, revision, revision, recurse); } public DirEntry[] list(String url, Revision revision, Revision pegRevision, boolean recurse) throws ClientException { final Collection allEntries = new ArrayList(); list(url, revision, pegRevision, JavaHLObjectFactory.infinityOrImmediates(recurse), SVNDirEntry.DIRENT_ALL, false, new ISVNDirEntryHandler() { public void handleDirEntry(SVNDirEntry dirEntry) { if (dirEntry.getRelativePath().length() != 0) { allEntries.add(JavaHLObjectFactory.createDirEntry(dirEntry)); } } }); return (DirEntry[]) allEntries.toArray(new DirEntry[allEntries.size()]); } public void list(String url, Revision revision, Revision pegRevision, int depth, int direntFields, boolean fetchLocks, ListCallback callback) throws ClientException { final ListCallback listCallback = callback; list(url, revision, pegRevision, depth, direntFields, fetchLocks, new ISVNDirEntryHandler() { public void handleDirEntry(SVNDirEntry dirEntry) { if (listCallback != null) { listCallback.doEntry(JavaHLObjectFactory.createDirEntry(dirEntry), JavaHLObjectFactory.createLock(dirEntry.getLock())); } } }); } private void list(String url, Revision revision, Revision pegRevision, int depth, int direntFields, boolean fetchLocks, ISVNDirEntryHandler handler) throws ClientException { SVNLogClient client = getSVNLogClient(); try { if (isURL(url)) { client.doList(SVNURL.parseURIEncoded(url), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), fetchLocks, JavaHLObjectFactory.getSVNDepth(depth), direntFields, handler); } else { client.doList(new File(url).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), fetchLocks, JavaHLObjectFactory.getSVNDepth(depth), direntFields, handler); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void username(String username) { myUserName = username; updateClientManager(); } public void password(String password) { myPassword = password; updateClientManager(); } public void setPrompt(PromptUserPassword prompt) { myPrompt = prompt; updateClientManager(); } private void updateClientManager() { File configDir = myConfigDir == null ? null : new File(myConfigDir); myOptions = SVNWCUtil.createDefaultOptions(configDir, true); myOptions.setConflictHandler(getConflictHandler()); myAuthenticationManager = SVNWCUtil.createDefaultAuthenticationManager(configDir, myUserName, myPassword, myOptions.isAuthStorageEnabled()); if (myPrompt != null) { myAuthenticationManager.setAuthenticationProvider(new JavaHLAuthenticationProvider(myPrompt)); } else { myAuthenticationManager.setAuthenticationProvider(null); } if (myAuthenticationManager instanceof DefaultSVNAuthenticationManager) { ((DefaultSVNAuthenticationManager)myAuthenticationManager).setRuntimeStorage(getClientCredentialsStorage()); } if (myClientManager != null) { myClientManager.dispose(); myClientManager.setAuthenticationManager(myAuthenticationManager); myClientManager.setOptions(myOptions); } } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd) throws ClientException { return logMessages(path, revisionStart, revisionEnd, true, false); } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy) throws ClientException { return logMessages(path, revisionStart, revisionEnd, stopOnCopy, false); } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath) throws ClientException { return logMessages(path, revisionStart, revisionEnd, stopOnCopy, discoverPath, 0); } public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, long limit) throws ClientException { final Collection entries = new ArrayList(); String[] revisionProperties = new String[]{SVNRevisionProperty.LOG, SVNRevisionProperty.DATE, SVNRevisionProperty.AUTHOR}; logMessages(path, revisionEnd, revisionStart, revisionEnd, stopOnCopy, discoverPath, false, revisionProperties, limit, new ISVNLogEntryHandler() { public void handleLogEntry(SVNLogEntry logEntry) { entries.add(JavaHLObjectFactory.createLogMessage(logEntry)); } } ); return (LogMessage[]) entries.toArray(new LogMessage[entries.size()]); } public void logMessages(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, boolean includeMergedRevisions, String[] revProps, long limit, LogMessageCallback callback) throws ClientException { final LogMessageCallback logMessageCallback = callback; logMessages(path, pegRevision, revisionStart, revisionEnd, stopOnCopy, discoverPath, includeMergedRevisions, revProps, limit, new ISVNLogEntryHandler() { public void handleLogEntry(SVNLogEntry logEntry) { JavaHLObjectFactory.handleLogMessage(logEntry, logMessageCallback); } } ); } private void logMessages(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, boolean includeMergeInfo, String[] revisionProperties, long limit, ISVNLogEntryHandler logEntryHandler) throws ClientException { SVNLogClient client = getSVNLogClient(); try { if (revisionEnd == null || revisionEnd.getKind() == RevisionKind.unspecified) { revisionEnd = Revision.HEAD; } if (revisionStart != null && revisionStart.getKind() == RevisionKind.unspecified) { revisionStart = Revision.getInstance(1); } if (isURL(path)) { if (revisionStart == null) { revisionStart = Revision.HEAD; } client.doLog( SVNURL.parseURIEncoded(path), new String[]{""}, JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), stopOnCopy, discoverPath, includeMergeInfo, limit, revisionProperties, logEntryHandler); } else { if (revisionStart == null) { revisionStart = Revision.BASE; } client.doLog( new File[]{new File(path).getAbsoluteFile()}, JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), JavaHLObjectFactory.getSVNRevision(pegRevision), stopOnCopy, discoverPath, includeMergeInfo, limit, revisionProperties, logEntryHandler); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } /** * @deprecated */ public void notification(Notify notify) { myNotify = notify; } public void notification2(Notify2 notify) { myNotify2 = notify; } public void setProgressListener(ProgressListener listener) { getDebugLog(); if (listener != null) { myProgressListener = new JavaHLProgressLog(listener); myDebugLog.addLogger(myProgressListener); } else if (myProgressListener != null) { myDebugLog.removeLogger(myProgressListener); myProgressListener = null; } } private void resetLog(){ if (myProgressListener != null) { myProgressListener.reset(); } } public void commitMessageHandler(CommitMessage messageHandler) { myMessageHandler = messageHandler; } public void setConflictResolver(ConflictResolverCallback listener) { myConflictResolverCallback = listener; mySVNConflictHandler = null; updateClientManager(); } public void remove(String[] path, String message, boolean force) throws ClientException { remove(path, message, force, false, null); } public void remove(String[] path, String message, boolean force, boolean keepLocal, Map revprops) throws ClientException { boolean areURLs = false; for (int i = 0; i < path.length; i++) { areURLs = areURLs || isURL(path[i]); } if (areURLs) { SVNCommitClient client = getSVNCommitClient(); SVNURL[] urls = new SVNURL[path.length]; for (int i = 0; i < urls.length; i++) { try { urls[i] = SVNURL.parseURIEncoded(path[i]); } catch (SVNException e) { throwException(e); } } try { SVNProperties revisionProperties = revprops == null ? null : SVNProperties.wrap(revprops); client.setCommitHandler(createCommitMessageHandler(true)); client.doDelete(urls, message, revisionProperties); } catch (SVNException e) { throwException(e); } finally { if (client != null) { client.setCommitHandler(null); } resetLog(); } } else { SVNWCClient client = getSVNWCClient(); for (int i = 0; i < path.length; i++) { try { client.doDelete(new File(path[i]).getAbsoluteFile(), force, !keepLocal, false); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } } } public void revert(String path, boolean recurse) throws ClientException { revert(path, JavaHLObjectFactory.infinityOrEmpty(recurse), null); } public void revert(String path, int depth, String[] changelists) throws ClientException { SVNWCClient client = getSVNWCClient(); try { client.doRevert(new File[] { new File(path).getAbsoluteFile() }, JavaHLObjectFactory.getSVNDepth(depth), JavaHLObjectFactory.getChangeListsCollection(changelists)); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void add(String path, boolean recurse) throws ClientException { add(path, recurse, false); } public void add(String path, boolean recurse, boolean force) throws ClientException { add(path, JavaHLObjectFactory.infinityOrEmpty(recurse), force, false, false); } public void add(String path, int depth, boolean force, boolean noIgnores, boolean addParents) throws ClientException { SVNWCClient wcClient = getSVNWCClient(); try { wcClient.doAdd(new File(path).getAbsoluteFile(), force, false, false, JavaHLObjectFactory.getSVNDepth(depth), noIgnores, addParents); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public long update(String path, Revision revision, boolean recurse) throws ClientException { long[] updated = update(new String[]{path}, revision, recurse, false); if (updated != null && updated.length > 0) { return updated[0]; } return -1; } public long[] update(String[] path, Revision revision, boolean recurse, boolean ignoreExternals) throws ClientException { return update(path, revision, JavaHLObjectFactory.unknownOrFiles(recurse), false, ignoreExternals, false); } public long update(String path, Revision revision, int depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { long[] updated = update(new String[]{path}, revision, depth, depthIsSticky, ignoreExternals, allowUnverObstructions); if (updated != null && updated.length > 0) { return updated[0]; } return -1; } public long[] update(String[] path, Revision revision, int depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { if (path == null || path.length == 0) { return new long[]{}; } long[] updated = new long[path.length]; SVNUpdateClient updater = getSVNUpdateClient(); boolean oldIgnore = updater.isIgnoreExternals(); updater.setIgnoreExternals(ignoreExternals); updater.setEventPathPrefix(""); SVNDepth svnDepth = JavaHLObjectFactory.getSVNDepth(depth); SVNRevision rev = JavaHLObjectFactory.getSVNRevision(revision); try { for (int i = 0; i < updated.length; i++) { updated[i] = updater.doUpdate(new File(path[i]).getAbsoluteFile(), rev, svnDepth, allowUnverObstructions, depthIsSticky); } } catch (SVNException e) { throwException(e); } finally { updater.setIgnoreExternals(oldIgnore); updater.setEventPathPrefix(null); resetLog(); SVNFileUtil.sleepForTimestamp(); } return updated; } public long commit(String[] path, String message, boolean recurse) throws ClientException { return commit(path, message, recurse, false); } public long commit(String[] path, String message, boolean recurse, boolean noUnlock) throws ClientException { return commit(path, message, JavaHLObjectFactory.infinityOrEmpty(recurse), noUnlock, false, null, null); } public long commit(String[] path, String message, int depth, boolean noUnlock, boolean keepChangelist, String[] changelists, Map revprops) throws ClientException { if (path == null || path.length == 0) { return 0; } SVNCommitClient client = getSVNCommitClient(); File[] files = new File[path.length]; for (int i = 0; i < path.length; i++) { files[i] = new File(path[i]).getAbsoluteFile(); } try { client.setCommitHandler(createCommitMessageHandler(false, false)); SVNDepth svnDepth = SVNDepth.fromID(depth); boolean recurse = SVNDepth.recurseFromDepth(svnDepth); SVNProperties revisionProperties = revprops == null ? null : SVNProperties.wrap(revprops); return client.doCommit(files, noUnlock, message, revisionProperties, changelists, keepChangelist, !recurse, svnDepth).getNewRevision(); } catch (SVNException e) { throwException(e); } finally { if (client != null) { client.setCommitHandler(null); } resetLog(); } return -1; } public long[] commit(String[] path, String message, boolean recurse, boolean noUnlock, boolean atomicCommit) throws ClientException { return commit(path, message, JavaHLObjectFactory.infinityOrEmpty(recurse), noUnlock, false, null, null, atomicCommit); } public long[] commit(String[] path, String message, int depth, boolean noUnlock, boolean keepChangelist, String[] changlelists, Map revprops, boolean atomicCommit) throws ClientException { if (path == null || path.length == 0) { return new long[0]; } SVNCommitClient client = getSVNCommitClient(); File[] files = new File[path.length]; for (int i = 0; i < path.length; i++) { files[i] = new File(path[i]).getAbsoluteFile(); } SVNCommitPacket[] packets = null; SVNCommitInfo[] commitResults = null; try { client.setCommitHandler(createCommitMessageHandler(false)); SVNDepth svnDepth = SVNDepth.fromID(depth); boolean recurse = SVNDepth.recurseFromDepth(svnDepth); packets = client.doCollectCommitItems(files, noUnlock, !recurse, svnDepth, atomicCommit, changlelists); if (packets != null) { if (packets.length == 1) { client.setEventHandler(new ISVNEventHandler() { public void checkCancelled() throws SVNCancelException { getEventListener().checkCancelled(); } public void handleEvent(SVNEvent event, double progress) throws SVNException { if (event.getAction() == SVNEventAction.SKIP && event.getErrorMessage() != null) { return; } getEventListener().handleEvent(event, progress); } }); } commitResults = client.doCommit(packets, noUnlock, keepChangelist, message, revprops != null ? SVNProperties.wrap(revprops) : null); } } catch (SVNException e) { throwException(e); } finally { if (packets != null) { for (int i = 0; i < packets.length; i++) { try { packets[i].dispose(); } catch (SVNException e) { } } } if (client != null) { client.setEventHandler(getEventListener()); client.setCommitHandler(null); } resetLog(); } if (commitResults != null && commitResults.length == 1) { if (commitResults[0].getNewRevision() < 0 && commitResults[0].getErrorMessage() != null) { // commit failed, not just accompanied by a error message // from the post-commit hook. throwException(new SVNException(commitResults[0].getErrorMessage())); } } if (commitResults != null && commitResults.length > 0) { long[] revisions = new long[commitResults.length]; for (int i = 0; i < commitResults.length; i++) { SVNCommitInfo result = commitResults[i]; revisions[i] = result.getNewRevision(); } return revisions; } return new long[0]; } public void copy(String srcPath, String destPath, String message, Revision revision) throws ClientException { copy(new CopySource[]{new CopySource(srcPath, revision, null)}, destPath, message, true, false, null); } public void copy(CopySource[] sources, String destPath, String message, boolean copyAsChild, boolean makeParents, Map revprops) throws ClientException { SVNCopySource[] copySources = getCopySources(sources, copyAsChild); copyOrMove(copySources, destPath, false, message, copyAsChild, makeParents, revprops); } public void move(String srcPath, String destPath, String message, boolean force) throws ClientException { move(new String[]{srcPath}, destPath, message, force, true, false, null); } public void move(String srcPath, String destPath, String message, Revision revision, boolean force) throws ClientException { move(new String[]{srcPath}, destPath, message, force, true, false, null); } public void move(String[] srcPaths, String destPath, String message, boolean force, boolean moveAsChild, boolean makeParents, Map revprops) throws ClientException { SVNCopySource[] copySources = getCopySources(srcPaths, moveAsChild); copyOrMove(copySources, destPath, true, message, moveAsChild, makeParents, revprops); } private SVNCopySource[] getCopySources(CopySource[] srcs, boolean copyAsChild) throws ClientException { if (srcs.length > 1 && !copyAsChild) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_MULTIPLE_SOURCES_DISALLOWED); SVNException ex = new SVNException(err); throwException(ex); } SVNCopySource[] sources = new SVNCopySource[srcs.length]; try { for (int i = 0; i < srcs.length; i++) { if (isURL(srcs[i].getPath())) { sources[i] = new SVNCopySource(JavaHLObjectFactory.getSVNRevision(srcs[i].getPegRevision()), JavaHLObjectFactory.getSVNRevision(srcs[i].getRevision()), SVNURL.parseURIEncoded(srcs[i].getPath())); } else { sources[i] = new SVNCopySource(JavaHLObjectFactory.getSVNRevision(srcs[i].getPegRevision()), JavaHLObjectFactory.getSVNRevision(srcs[i].getRevision()), new File(srcs[i].getPath()).getAbsoluteFile()); } } } catch (SVNException e) { throwException(e); } finally { resetLog(); } return sources; } private SVNCopySource[] getCopySources(String[] srcPaths, boolean copyAsChild) throws ClientException { if (srcPaths.length > 1 && !copyAsChild) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_MULTIPLE_SOURCES_DISALLOWED); SVNException ex = new SVNException(err); throwException(ex); } SVNCopySource[] sources = new SVNCopySource[srcPaths.length]; try { for (int i = 0; i < srcPaths.length; i++) { if (isURL(srcPaths[i])) { sources[i] = new SVNCopySource(SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNURL.parseURIEncoded(srcPaths[i])); } else { sources[i] = new SVNCopySource(SVNRevision.UNDEFINED, SVNRevision.HEAD, new File(srcPaths[i]).getAbsoluteFile()); } } } catch (SVNException e) { throwException(e); } finally { resetLog(); } return sources; } private void copyOrMove(SVNCopySource[] sources, String destPath, boolean isMove, String message, boolean copyAsChild, boolean makeParents, Map revprops) throws ClientException { SVNCopyClient client = getSVNCopyClient(); try { if (isURL(destPath)) { SVNProperties revisionProperties = revprops == null ? null : SVNProperties.wrap(revprops); boolean isURLs = sources.length > 0 && sources[0].isURL(); client.setCommitHandler(createCommitMessageHandler(isURLs)); client.doCopy(sources, SVNURL.parseURIEncoded(destPath), isMove, makeParents, !copyAsChild, message, revisionProperties); } else { client.doCopy(sources, new File(destPath).getAbsoluteFile(), isMove, makeParents, !copyAsChild); } } catch (SVNException e) { throwException(e); } finally { if (client != null) { client.setCommitHandler(null); } resetLog(); } } public void mkdir(String[] path, String message) throws ClientException { mkdir(path, message, false, null); } public void mkdir(String[] path, String message, boolean makeParents, Map revprops) throws ClientException { SVNCommitClient client = getSVNCommitClient(); List urls = new ArrayList(); List paths = new ArrayList(); for (int i = 0; i < path.length; i++) { if (isURL(path[i])) { try { urls.add(SVNURL.parseURIEncoded(path[i])); } catch (SVNException e) { throwException(e); } } else { paths.add(new File(path[i])); } } SVNURL[] svnURLs = (SVNURL[]) urls.toArray(new SVNURL[urls.size()]); File[] files = (File[]) paths.toArray(new File[paths.size()]); if (svnURLs.length > 0) { try { SVNProperties revisionProperties = revprops == null ? null : SVNProperties.wrap(revprops); client.setCommitHandler(createCommitMessageHandler(true, true)); client.doMkDir(svnURLs, message, revisionProperties, makeParents); } catch (SVNException e) { throwException(e); } finally { if (client != null) { client.setCommitHandler(null); } } } if (files.length > 0) { for (int i = 0; i < files.length; i++) { File file = files[i]; try { getSVNWCClient().doAdd(file, false, true, false, SVNDepth.EMPTY, false, false); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } } } public void cleanup(String path) throws ClientException { SVNWCClient client = getSVNWCClient(); try { client.doCleanup(new File(path).getAbsoluteFile()); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void resolved(String path, boolean recurse) throws ClientException { resolve(path, JavaHLObjectFactory.infinityOrEmpty(recurse), ConflictResult.chooseMerged); } public void resolve(String path, int depth, int conflictResult) throws ClientException { SVNWCClient client = getSVNWCClient(); try { client.doResolve(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNDepth(depth), JavaHLObjectFactory.getSVNConflictChoice(conflictResult)); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public long doExport(String srcPath, String destPath, Revision revision, boolean force) throws ClientException { return doExport(srcPath, destPath, revision, revision, force, false, true, null); } public long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, boolean recurse, String nativeEOL) throws ClientException { return doExport(srcPath, destPath, revision, pegRevision, force, ignoreExternals, JavaHLObjectFactory.infinityOrFiles(recurse), nativeEOL); } public long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, int depth, String nativeEOL) throws ClientException { SVNUpdateClient updater = getSVNUpdateClient(); boolean oldIgnore = updater.isIgnoreExternals(); updater.setIgnoreExternals(ignoreExternals); try { if (isURL(srcPath)) { return updater.doExport(SVNURL.parseURIEncoded(srcPath), new File(destPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), nativeEOL, force, JavaHLObjectFactory.getSVNDepth(depth)); } return updater.doExport(new File(srcPath).getAbsoluteFile(), new File(destPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), nativeEOL, force, JavaHLObjectFactory.getSVNDepth(depth)); } catch (SVNException e) { throwException(e); } finally { updater.setIgnoreExternals(oldIgnore); resetLog(); } return -1; } public void doImport(String path, String url, String message, boolean recurse) throws ClientException { doImport(path, url, message, JavaHLObjectFactory.infinityOrFiles(recurse), false, false, null); } public void doImport(String path, String url, String message, int depth, boolean noIgnore, boolean ignoreUnknownNodeTypes, Map revprops) throws ClientException { SVNCommitClient commitClient = getSVNCommitClient(); try { commitClient.setCommitHandler(createCommitMessageHandler(false, true)); SVNProperties revisionProperties = revprops == null ? null : SVNProperties.wrap(revprops); commitClient.doImport(new File(path), SVNURL.parseURIEncoded(url), message, revisionProperties, !noIgnore, ignoreUnknownNodeTypes, JavaHLObjectFactory.getSVNDepth(depth)); } catch (SVNException e) { throwException(e); } finally { if (commitClient != null) { commitClient.setCommitHandler(null); } resetLog(); } } public void merge(String path, Revision pegRevision, RevisionRange[] revisions, String localPath, boolean force, int depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { List rangesToMerge = new ArrayList(revisions.length); for (int i = 0; i < revisions.length; i++) { if (revisions[i].getFromRevision().getKind() == RevisionKind.unspecified && revisions[i].getToRevision().getKind() == RevisionKind.unspecified) { SVNRevisionRange range = new SVNRevisionRange(SVNRevision.create(1), SVNRevision.HEAD); rangesToMerge.add(range); } else { rangesToMerge.add(JavaHLObjectFactory.getSVNRevisionRange(revisions[i])); } } merge(path, pegRevision, rangesToMerge, localPath, force, depth, ignoreAncestry, dryRun, recordOnly); } public void merge(String path, Revision pegRevision, Revision revision1, Revision revision2, String localPath, boolean force, boolean recurse, boolean ignoreAncestry, boolean dryRun) throws ClientException { List rangesToMerge = new LinkedList(); rangesToMerge.add(new SVNRevisionRange(JavaHLObjectFactory.getSVNRevision(revision1), JavaHLObjectFactory.getSVNRevision(revision2))); merge(path, pegRevision, rangesToMerge, localPath, force, JavaHLObjectFactory.infinityOrFiles(recurse), ignoreAncestry, dryRun, false); } private void merge(String path, Revision pegRevision, List rangesToMerge, String localPath, boolean force, int depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { SVNDiffClient differ = getSVNDiffClient(); try { if (isURL(path)) { SVNURL url = SVNURL.parseURIEncoded(path); differ.doMerge(url, JavaHLObjectFactory.getSVNRevision(pegRevision), rangesToMerge, new File(localPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, force, dryRun, recordOnly); } else { differ.doMerge(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), rangesToMerge, new File(localPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, force, dryRun, recordOnly); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, boolean recurse) throws ClientException { merge(path1, revision1, path2, revision2, localPath, force, recurse, false, false); } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, boolean recurse, boolean ignoreAncestry, boolean dryRun) throws ClientException { merge(path1, revision1, path2, revision2, localPath, force, JavaHLObjectFactory.infinityOrFiles(recurse), ignoreAncestry, dryRun, false); } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, int depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { SVNDiffClient differ = getSVNDiffClient(); try { if (isURL(path1) && isURL(path2)) { SVNURL url1 = SVNURL.parseURIEncoded(path1); SVNURL url2 = SVNURL.parseURIEncoded(path2); differ.doMerge(url1, JavaHLObjectFactory.getSVNRevision(revision1), url2, JavaHLObjectFactory.getSVNRevision(revision2), new File(localPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, force, dryRun, recordOnly); } else if (isURL(path1)) { SVNURL url1 = SVNURL.parseURIEncoded(path1); File file2 = new File(path2).getAbsoluteFile(); differ.doMerge(url1, JavaHLObjectFactory.getSVNRevision(revision1), file2, JavaHLObjectFactory.getSVNRevision(revision2), new File(localPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, force, dryRun, recordOnly); } else if (isURL(path2)) { SVNURL url2 = SVNURL.parseURIEncoded(path2); File file1 = new File(path1).getAbsoluteFile(); differ.doMerge(file1, JavaHLObjectFactory.getSVNRevision(revision1), url2, JavaHLObjectFactory.getSVNRevision(revision2), new File(localPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, force, dryRun, recordOnly); } else { File file1 = new File(path1).getAbsoluteFile(); File file2 = new File(path2).getAbsoluteFile(); differ.doMerge(file1, JavaHLObjectFactory.getSVNRevision(revision1), file2, JavaHLObjectFactory.getSVNRevision(revision2), new File(localPath).getAbsoluteFile(), JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, force, dryRun, recordOnly); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void mergeReintegrate(String path, Revision pegRevision, String localPath, boolean dryRun) throws ClientException { SVNDiffClient diffClient = getSVNDiffClient(); File dstPath = new File(localPath); try { if (isURL(path)){ SVNURL url = SVNURL.parseURIEncoded(path); diffClient.doMergeReIntegrate(url, JavaHLObjectFactory.getSVNRevision(pegRevision), dstPath, dryRun); } else { File file = new File(path); diffClient.doMergeReIntegrate(file, JavaHLObjectFactory.getSVNRevision(pegRevision), dstPath, dryRun); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public String[] suggestMergeSources(String path, Revision pegRevision) throws SubversionException { SVNDiffClient client = getSVNDiffClient(); Collection mergeSrcURLs = null; try { if (isURL(path)) { SVNURL url = SVNURL.parseURIEncoded(path); mergeSrcURLs = client.doSuggestMergeSources(url, JavaHLObjectFactory.getSVNRevision(pegRevision)); } else { mergeSrcURLs = client.doSuggestMergeSources(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision)); } if (mergeSrcURLs != null) { String[] stringURLs = new String[mergeSrcURLs.size()]; int i = 0; for (Iterator urls = mergeSrcURLs.iterator(); urls.hasNext();) { SVNURL mergeSrcURL = (SVNURL) urls.next(); stringURLs[i++] = mergeSrcURL.toString(); } return stringURLs; } return null; } catch (SVNException e) { throwException(e); } finally { resetLog(); } return null; } public Mergeinfo getMergeinfo(String path, Revision revision) throws SubversionException { SVNDiffClient client = getSVNDiffClient(); Map mergeInfo = null; try { if (isURL(path)) { mergeInfo = client.doGetMergedMergeInfo(SVNURL.parseURIEncoded(path), JavaHLObjectFactory.getSVNRevision(revision)); } else { mergeInfo = client.doGetMergedMergeInfo(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(revision)); } return JavaHLObjectFactory.createMergeInfo(mergeInfo); } catch (SVNException e) { throwException(e); } finally { resetLog(); } return null; } public void getMergeinfoLog(int kind, String pathOrUrl, Revision pegRevision, String mergeSourceUrl, Revision srcPegRevision, boolean discoverChangedPaths, String[] revprops, final LogMessageCallback callback) throws ClientException { SVNDiffClient client = getSVNDiffClient(); ISVNLogEntryHandler handler = new ISVNLogEntryHandler() { public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { JavaHLObjectFactory.handleLogMessage(logEntry, callback); } }; SVNRevision pegRev = JavaHLObjectFactory.getSVNRevision(pegRevision); SVNRevision srcPegRev = JavaHLObjectFactory.getSVNRevision(srcPegRevision); try { SVNURL mergeSrcURL = SVNURL.parseURIEncoded(mergeSourceUrl); if (isURL(pathOrUrl)) { SVNURL url = SVNURL.parseURIEncoded(pathOrUrl); if (kind == MergeinfoLogKind.eligible) { client.doGetLogEligibleMergeInfo(url, pegRev, mergeSrcURL, srcPegRev, discoverChangedPaths, revprops, handler); } else if (kind == MergeinfoLogKind.merged) { client.doGetLogMergedMergeInfo(url, pegRev, mergeSrcURL, srcPegRev, discoverChangedPaths, revprops, handler); } } else { File path = new File(pathOrUrl).getAbsoluteFile(); if (kind == MergeinfoLogKind.eligible) { client.doGetLogEligibleMergeInfo(path, pegRev, mergeSrcURL, srcPegRev, discoverChangedPaths, revprops, handler); } else if (kind == MergeinfoLogKind.merged) { client.doGetLogMergedMergeInfo(path, pegRev, mergeSrcURL, srcPegRev, discoverChangedPaths, revprops, handler); } } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public PropertyData[] properties(String path) throws ClientException { return properties(path, null); } public PropertyData[] properties(String path, Revision revision) throws ClientException { return properties(path, revision, revision); } public PropertyData[] properties(String path, Revision revision, Revision pegRevision) throws ClientException { return properties(path, revision, pegRevision, SVNDepth.EMPTY, null); } public void properties(String path, Revision revision, Revision pegRevision, int depth, String[] changelists, ProplistCallback callback) throws ClientException { if (path == null || callback == null) { return; } PropertyData[] properties = properties(path, revision, pegRevision, JavaHLObjectFactory.getSVNDepth(depth), changelists); Map propsMap = new SVNHashMap(); for (int i = 0; i < properties.length; i++) { propsMap.put(properties[i].getName(), properties[i].getData()); } callback.singlePath(path, propsMap); } private PropertyData[] properties(String path, Revision revision, Revision pegRevision, SVNDepth depth, String[] changelists) throws ClientException { if (path == null) { return null; } SVNWCClient client = getSVNWCClient(); SVNRevision svnRevision = JavaHLObjectFactory.getSVNRevision(revision); SVNRevision svnPegRevision = JavaHLObjectFactory.getSVNRevision(pegRevision); JavaHLPropertyHandler propHandler = new JavaHLPropertyHandler(myOwner); try { if (isURL(path)) { client.doGetProperty(SVNURL.parseURIEncoded(path), null, svnPegRevision, svnRevision, depth, propHandler); } else { client.doGetProperty(new File(path).getAbsoluteFile(), null, svnPegRevision, svnRevision, depth, propHandler, JavaHLObjectFactory.getChangeListsCollection(changelists)); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } return propHandler.getAllPropertyData(); } public void propertySet(String path, String name, byte[] value, boolean recurse) throws ClientException { propertySet(path, name, value, recurse, false); } public void propertySet(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException { propertySet(path, name, SVNPropertyValue.create(name, value), JavaHLObjectFactory.infinityOrEmpty(recurse), force, null, null); } public void propertySet(String path, String name, String value, boolean recurse) throws ClientException { propertySet(path, name, value, recurse, false); } public void propertySet(String path, String name, String value, boolean recurse, boolean force) throws ClientException { propertySet(path, name, value, JavaHLObjectFactory.infinityOrEmpty(recurse), null, force, null); } public void propertySet(String path, String name, String value, int depth, String[] changelists, boolean force, Map revprops) throws ClientException { propertySet(path, name, SVNPropertyValue.create(value), depth, force, changelists, revprops); } private void propertySet(String path, String name, SVNPropertyValue value, int depth, boolean force, String[] changelists, Map revprops) throws ClientException { SVNWCClient client = getSVNWCClient(); if (isURL(path)) { try { SVNProperties revisionProperties = revprops == null ? null : SVNProperties.wrap(revprops); client.setCommitHandler(createCommitMessageHandler(true)); client.doSetProperty(SVNURL.parseURIEncoded(path), name, value, SVNRevision.HEAD, "", revisionProperties, force, ISVNPropertyHandler.NULL); } catch (SVNException e) { throwException(e); } finally { if (client != null) { client.setCommitHandler(null); } resetLog(); } } else { try { client.doSetProperty(new File(path).getAbsoluteFile(), name, value, force, JavaHLObjectFactory.getSVNDepth(depth), ISVNPropertyHandler.NULL, JavaHLObjectFactory.getChangeListsCollection(changelists)); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } } public void propertyRemove(String path, String name, boolean recurse) throws ClientException { propertyRemove(path, name, JavaHLObjectFactory.infinityOrEmpty(recurse), null); } public void propertyRemove(String path, String name, int depth, String[] changelists) throws ClientException { SVNWCClient client = getSVNWCClient(); try { client.doSetProperty(new File(path).getAbsoluteFile(), name, null, false, JavaHLObjectFactory.getSVNDepth(depth), ISVNPropertyHandler.NULL, JavaHLObjectFactory.getChangeListsCollection(changelists)); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public PropertyData propertyGet(String path, String name) throws ClientException { return propertyGet(path, name, null); } public PropertyData propertyGet(String path, String name, Revision revision) throws ClientException { return propertyGet(path, name, revision, revision); } public PropertyData propertyGet(String path, String name, Revision revision, Revision pegRevision) throws ClientException { if (name == null || name.equals("")) { return null; } SVNWCClient client = getSVNWCClient(); SVNRevision svnRevision = JavaHLObjectFactory.getSVNRevision(revision); SVNRevision svnPegRevision = JavaHLObjectFactory.getSVNRevision(pegRevision); JavaHLPropertyHandler retriever = new JavaHLPropertyHandler(myOwner); try { if (isURL(path)) { client.doGetProperty(SVNURL.parseURIEncoded(path), name, svnPegRevision, svnRevision, SVNDepth.EMPTY, retriever); } else { client.doGetProperty(new File(path).getAbsoluteFile(), name, svnPegRevision, svnRevision, SVNDepth.EMPTY, retriever, null); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } return retriever.getPropertyData(); } public void propertyCreate(String path, String name, String value, boolean recurse) throws ClientException { propertyCreate(path, name, value, recurse, false); } public void propertyCreate(String path, String name, byte[] value, boolean recurse) throws ClientException { propertyCreate(path, name, value, recurse, false); } public void propertyCreate(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException { propertyCreate(path, name, SVNPropertyValue.create(name, value), JavaHLObjectFactory.infinityOrEmpty(recurse), null, force); } public void propertyCreate(String path, String name, String value, boolean recurse, boolean force) throws ClientException { propertySet(path, name, value, recurse, force); } public void propertyCreate(String path, String name, String value, int depth, String[] changelists, boolean force) throws ClientException { propertyCreate(path, name, SVNPropertyValue.create(value), depth, changelists, force); } private void propertyCreate(String path, String name, SVNPropertyValue value, int depth, String[] changelists, boolean force) throws ClientException { SVNWCClient client = getSVNWCClient(); try { client.doSetProperty(new File(path).getAbsoluteFile(), name, value, force, JavaHLObjectFactory.getSVNDepth(depth), ISVNPropertyHandler.NULL, JavaHLObjectFactory.getChangeListsCollection(changelists)); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public PropertyData revProperty(String path, String name, Revision rev) throws ClientException { if (name == null || name.equals("")) { return null; } SVNWCClient client = getSVNWCClient(); SVNRevision svnRevision = JavaHLObjectFactory.getSVNRevision(rev); JavaHLPropertyHandler retriever = new JavaHLPropertyHandler(myOwner); try { if (isURL(path)) { client.doGetRevisionProperty(SVNURL.parseURIEncoded(path), name, svnRevision, retriever); } else { client.doGetRevisionProperty(new File(path).getAbsoluteFile(), name, svnRevision, retriever); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } return retriever.getPropertyData(); } public PropertyData[] revProperties(String path, Revision rev) throws ClientException { if (path == null) { return null; } SVNWCClient client = getSVNWCClient(); SVNRevision svnRevision = JavaHLObjectFactory.getSVNRevision(rev); JavaHLPropertyHandler propHandler = new JavaHLPropertyHandler(myOwner); try { if (isURL(path)) { client.doGetRevisionProperty(SVNURL.parseURIEncoded(path), null, svnRevision, propHandler); } else { client.doGetRevisionProperty(new File(path).getAbsoluteFile(), null, svnRevision, propHandler); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } return propHandler.getAllPropertyData(); } public void setRevProperty(String path, String name, Revision rev, String value, boolean force) throws ClientException { if (name == null || name.equals("")) { return; } SVNWCClient client = getSVNWCClient(); SVNRevision svnRevision = JavaHLObjectFactory.getSVNRevision(rev); SVNPropertyValue propertyValue = SVNPropertyValue.create(value); try { if (isURL(path)) { client.doSetRevisionProperty(SVNURL.parseURIEncoded(path), svnRevision, name, propertyValue, force, ISVNPropertyHandler.NULL); } else { client.doSetRevisionProperty(new File(path).getAbsoluteFile(), svnRevision, name, propertyValue, force, ISVNPropertyHandler.NULL); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public byte[] fileContent(String path, Revision revision) throws ClientException { return fileContent(path, revision, revision); } public byte[] fileContent(String path, Revision revision, Revision pegRevision) throws ClientException { SVNWCClient client = getSVNWCClient(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (isURL(path)) { client.doGetFileContents(SVNURL.parseURIEncoded(path), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), true, baos); } else { client.doGetFileContents(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), true, baos); } return baos.toByteArray(); } catch (SVNException e) { throwException(e); } finally { resetLog(); } return null; } public void streamFileContent(String path, Revision revision, Revision pegRevision, int bufferSize, OutputStream stream) throws ClientException { SVNWCClient client = getSVNWCClient(); try { if (isURL(path)) { client.doGetFileContents(SVNURL.parseURIEncoded(path), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), true, stream); } else { client.doGetFileContents(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), true, stream); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void relocate(String from, String to, String path, boolean recurse) throws ClientException { SVNUpdateClient client = getSVNUpdateClient(); try { client.doRelocate(new File(path).getAbsoluteFile(), SVNURL.parseURIEncoded(from), SVNURL.parseURIEncoded(to), recurse); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void blame(String path, Revision revisionStart, Revision revisionEnd, BlameCallback callback) throws ClientException { blame(path, revisionEnd, revisionStart, revisionEnd, callback); } public byte[] blame(String path, Revision revisionStart, Revision revisionEnd) throws ClientException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ISVNAnnotateHandler handler = new ISVNAnnotateHandler() { public void handleLine(Date date, long revision, String author, String line) { StringBuffer result = new StringBuffer(); String revStr = revision >= 0 ? SVNFormatUtil.formatString(Long.toString(revision), 6, false) : " -"; String authorStr = author != null ? SVNFormatUtil.formatString(author, 10, false) : " -"; result.append(revStr); result.append(' '); result.append(authorStr); result.append(' '); result.append(line); try { baos.write(result.toString().getBytes()); baos.write('\n'); } catch (IOException e) { } } public void handleLine(Date date, long revision, String author, String line, Date mergedDate, long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException { handleLine(mergedDate == null ? date : mergedDate, mergedRevision < 0 ? revision : mergedRevision, mergedAuthor == null ? author : mergedAuthor, line); } public boolean handleRevision(Date date, long revision, String author, File contents) throws SVNException { return false; } public void handleEOF() { } }; blame(path, revisionEnd, revisionStart, revisionEnd, false, false, handler); return baos.toByteArray(); } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, BlameCallback callback) throws ClientException { final BlameCallback blameCallback = callback; ISVNAnnotateHandler handler = new ISVNAnnotateHandler() { public void handleLine(Date date, long revision, String author, String line) { if (blameCallback != null) { blameCallback.singleLine(date, revision, author, line); } } public void handleLine(Date date, long revision, String author, String line, Date mergedDate, long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException { handleLine(date, revision, author, line); } public boolean handleRevision(Date date, long revision, String author, File contents) throws SVNException { return false; } public void handleEOF() { } }; blame(path, pegRevision, revisionStart, revisionEnd, false, false, handler); } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, BlameCallback2 callback) throws ClientException { final BlameCallback2 blameCallback = callback; ISVNAnnotateHandler handler = new ISVNAnnotateHandler() { public void handleLine(Date date, long revision, String author, String line) { } public void handleLine(Date date, long revision, String author, String line, Date mergedDate, long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException { if (blameCallback != null) { blameCallback.singleLine(date, revision, author, mergedDate, mergedRevision, mergedAuthor, mergedPath, line); } } public boolean handleRevision(Date date, long revision, String author, File contents) throws SVNException { return false; } public void handleEOF() { } }; blame(path, pegRevision, revisionStart, revisionEnd, ignoreMimeType, includeMergedRevisions, handler); } private void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, ISVNAnnotateHandler handler) throws ClientException { SVNLogClient client = getSVNLogClient(); try { if (isURL(path)) { client.doAnnotate(SVNURL.parseURIEncoded(path), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), ignoreMimeType, includeMergedRevisions, handler, null); } else { client.doAnnotate(new File(path).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revisionStart), JavaHLObjectFactory.getSVNRevision(revisionEnd), ignoreMimeType, includeMergedRevisions, handler, null); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void dispose() { if (myClientManager != null) { myClientManager.dispose(); myClientManager = null; } synchronized (SVNClientImpl.class) { ourInstanceCount--; if (ourInstanceCount <= 0) { ourInstanceCount = 0; SVNSSHConnector.shutdown(); } } } public void setConfigDirectory(String configDir) throws ClientException { myConfigDir = configDir; updateClientManager(); } public String getConfigDirectory() throws ClientException { return myConfigDir; } public void cancelOperation() throws ClientException { myCancelOperation = true; } public Info info(String path) throws ClientException { SVNWCClient client = getSVNWCClient(); try { if (isURL(path)) { return JavaHLObjectFactory.createInfo(client.doInfo(SVNURL.parseURIEncoded(path), SVNRevision.UNDEFINED, SVNRevision.UNDEFINED)); } return JavaHLObjectFactory.createInfo(client.doInfo(new File(path).getAbsoluteFile(), SVNRevision.UNDEFINED)); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.UNVERSIONED_RESOURCE) { return null; } throwException(e); } finally { resetLog(); } return null; } public void lock(String[] path, String comment, boolean force) throws ClientException { boolean allFiles = true; for (int i = 0; i < path.length; i++) { allFiles = allFiles && !isURL(path[i]); } try { if (allFiles) { File[] files = new File[path.length]; for (int i = 0; i < files.length; i++) { files[i] = new File(path[i]).getAbsoluteFile(); } getSVNWCClient().doLock(files, force, comment); } else { SVNURL[] urls = new SVNURL[path.length]; for (int i = 0; i < urls.length; i++) { urls[i] = SVNURL.parseURIEncoded(path[i]); } getSVNWCClient().doLock(urls, force, comment); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void unlock(String[] path, boolean force) throws ClientException { boolean allFiles = true; for (int i = 0; i < path.length; i++) { allFiles = allFiles && !isURL(path[i]); } try { if (allFiles) { File[] files = new File[path.length]; for (int i = 0; i < files.length; i++) { files[i] = new File(path[i]).getAbsoluteFile(); } getSVNWCClient().doUnlock(files, force); } else { SVNURL[] urls = new SVNURL[path.length]; for (int i = 0; i < urls.length; i++) { urls[i] = SVNURL.parseURIEncoded(path[i]); } getSVNWCClient().doUnlock(urls, force); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public String getVersionInfo(String path, String trailUrl, boolean lastChanged) throws ClientException { try { return getSVNWCClient().doGetWorkingCopyID(new File(path).getAbsoluteFile(), trailUrl); } catch (SVNException e) { throwException(e); } finally { resetLog(); } return null; } public static String version() { return Version.getVersionString(); } public static int versionMajor() { return Version.getMajorVersion(); } public static int versionMinor() { return Version.getMinorVersion(); } public static int versionMicro() { return Version.getMicroVersion(); } public static long versionRevisionNumber() { return org.tmatesoft.svn.util.Version.getRevisionNumber(); } public static void enableLogging(int logLevel, String logFilePath) { try { JavaHLDebugLog.getInstance().enableLogging(logLevel, new File(logFilePath), new DefaultSVNDebugFormatter()); } catch (SVNException e) { JavaHLDebugLog.getInstance().logSevere(SVNLogType.DEFAULT, e); } } /** * @deprecated */ protected Notify getNotify() { return myNotify; } protected Notify2 getNotify2() { return myNotify2; } protected ISVNEventHandler getEventListener() { if (mySVNEventListener == null) { mySVNEventListener = new ISVNEventHandler() { public void handleEvent(SVNEvent event, double progress) { if (event.getAction() == SVNEventAction.UPGRADE) { return; } String path = null; if (event.getFile() != null) { path = event.getFile().getAbsolutePath(); if (path != null) { path = path.replace(File.separatorChar, '/'); } } if (path == null) { path = ""; } if (myNotify != null && event.getErrorMessage() == null) { final int actionId = JavaHLObjectFactory.getNotifyActionValue(event.getAction()); if (actionId != -1) { myNotify.onNotify( path, actionId, JavaHLObjectFactory.getNodeKind(event.getNodeKind()), event.getMimeType(), JavaHLObjectFactory.getStatusValue(event.getContentsStatus()), JavaHLObjectFactory.getStatusValue(event.getPropertiesStatus()), event.getRevision() ); } } if (myNotify2 != null) { NotifyInformation info = JavaHLObjectFactory.createNotifyInformation(event, path); if (info != null) { myNotify2.onNotify(info); } } } public void checkCancelled() throws SVNCancelException { if (myCancelOperation) { myCancelOperation = false; SVNErrorManager.cancel("operation cancelled", SVNLogType.DEFAULT); } } }; } return mySVNEventListener; } protected ISVNConflictHandler getConflictHandler() { if (mySVNConflictHandler == null && myConflictResolverCallback != null) { mySVNConflictHandler = new ISVNConflictHandler() { public SVNConflictResult handleConflict(SVNConflictDescription conflictDescription) throws SVNException { SVNConflictResult result = null; if (myConflictResolverCallback != null) { ConflictDescriptor descriptor = JavaHLObjectFactory.createConflictDescription(conflictDescription); try { result = JavaHLObjectFactory.getSVNConflictResult(myConflictResolverCallback.resolve(descriptor)); } catch (SubversionException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.UNKNOWN, e), e, SVNLogType.DEFAULT); } } return result; } }; } return mySVNConflictHandler; } public ISVNOptions getOptions() { if (myOptions == null) { File configDir = myConfigDir == null ? null : new File(myConfigDir); myOptions = SVNWCUtil.createDefaultOptions(configDir, true); myOptions.setConflictHandler(getConflictHandler()); } return myOptions; } protected SVNClientManager getClientManager() { if (myClientManager == null) { updateClientManager(); myClientManager = SVNClientManager.newInstance(myOptions, new DefaultSVNRepositoryPool(myAuthenticationManager, myOptions)); myClientManager.setDebugLog(getDebugLog()); myClientManager.setEventHandler(getEventListener()); } return myClientManager; } protected SVNCommitClient getSVNCommitClient() { return getClientManager().getCommitClient(); } protected SVNUpdateClient getSVNUpdateClient() { return getClientManager().getUpdateClient(); } protected SVNStatusClient getSVNStatusClient() { return getClientManager().getStatusClient(); } protected SVNWCClient getSVNWCClient() { return getClientManager().getWCClient(); } protected SVNDiffClient getSVNDiffClient() { return getClientManager().getDiffClient(); } protected SVNCopyClient getSVNCopyClient() { return getClientManager().getCopyClient(); } protected SVNLogClient getSVNLogClient() { return getClientManager().getLogClient(); } protected SVNChangelistClient getChangelistClient() { return getClientManager().getChangelistClient(); } protected CommitMessage getCommitMessage() { return myMessageHandler; } protected ISVNCommitHandler createCommitMessageHandler(final boolean isURLsOnly) { return createCommitMessageHandler(isURLsOnly, false); } protected ISVNCommitHandler createCommitMessageHandler(final boolean isURLsOnly, final boolean isImport) { if (myMessageHandler != null) { return new ISVNCommitHandler() { public String getCommitMessage(String cmessage, SVNCommitItem[] commitables) { CommitItem[] items = JavaHLObjectFactory.getCommitItems(commitables, isImport, isURLsOnly); return myMessageHandler.getLogMessage(items); } public SVNProperties getRevisionProperties(String message, SVNCommitItem[] commitables, SVNProperties revisionProperties) throws SVNException { return revisionProperties == null ? new SVNProperties() : revisionProperties; } }; } return null; } protected void throwException(SVNException e) throws ClientException { JavaHLObjectFactory.throwException(e, this); } protected static boolean isURL(String pathOrUrl) { return SVNPathUtil.isURL(pathOrUrl); } public String getAdminDirectoryName() { return SVNFileUtil.getAdminDirectoryName(); } public boolean isAdminDirectory(String name) { return name != null && (SVNFileUtil.isWindows) ? SVNFileUtil.getAdminDirectoryName().equalsIgnoreCase(name) : SVNFileUtil.getAdminDirectoryName().equals(name); } public org.tigris.subversion.javahl.Version getVersion() { return SVNClientImplVersion.getInstance(); } public long doSwitch(String path, String url, Revision revision, boolean recurse) throws ClientException { return doSwitch(path, url, revision, Revision.HEAD, JavaHLObjectFactory.unknownOrFiles(recurse), false, false, false); } public long doSwitch(String path, String url, Revision revision, Revision pegRevision, int depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { SVNUpdateClient updater = getSVNUpdateClient(); try { return updater.doSwitch(new File(path).getAbsoluteFile(), SVNURL.parseURIEncoded(url), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), JavaHLObjectFactory.getSVNDepth(depth), allowUnverObstructions, depthIsSticky); } catch (SVNException e) { throwException(e); } finally { resetLog(); } return -1; } public void addToChangelist(String[] paths, String changelist, int depth, String[] changelists) throws ClientException { if (paths == null || paths.length == 0 || changelist == null || "".equals(changelist)) { return; } SVNChangelistClient changelistClient = getChangelistClient(); File[] files = new File[paths.length]; for (int i = 0; i < paths.length; i++) { files[i] = new File(paths[i]).getAbsoluteFile(); } try { changelistClient.doAddToChangelist(files, JavaHLObjectFactory.getSVNDepth(depth), changelist, changelists); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void removeFromChangelists(String[] paths, int depth, String[] changelists) throws ClientException { if (paths == null || paths.length == 0 || changelists == null) { return; } File[] files = new File[paths.length]; for (int i = 0; i < paths.length; i++) { files[i] = new File(paths[i]).getAbsoluteFile(); } SVNChangelistClient changelistClient = getChangelistClient(); try { changelistClient.doRemoveFromChangelist(files, JavaHLObjectFactory.getSVNDepth(depth), changelists); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void getChangelists(String rootPath, String[] changelists, int depth, final ChangelistCallback callback) throws ClientException { if (changelists == null) { return; } ISVNChangelistHandler handler = new ISVNChangelistHandler() { public void handle(File path, String changelistName) { if (callback != null) { String filePath = path.getAbsolutePath().replace(File.separatorChar, '/'); callback.doChangelist(filePath, changelistName); } } }; SVNChangelistClient changelistClient = getChangelistClient(); try { changelistClient.doGetChangeLists(new File(rootPath).getAbsoluteFile(), JavaHLObjectFactory.getChangeListsCollection(changelists), JavaHLObjectFactory.getSVNDepth(depth), handler); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public long checkout(String moduleName, String destPath, Revision revision, boolean recurse) throws ClientException { return checkout(moduleName, destPath, revision, revision, recurse, false); } public long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, boolean recurse, boolean ignoreExternals) throws ClientException { return checkout(moduleName, destPath, revision, pegRevision, JavaHLObjectFactory.infinityOrFiles(recurse), ignoreExternals, false); } public long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, int depth, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { SVNUpdateClient updater = getSVNUpdateClient(); boolean oldIgnoreExternals = updater.isIgnoreExternals(); updater.setIgnoreExternals(ignoreExternals); try { File path = new File(destPath).getAbsoluteFile(); return updater.doCheckout(SVNURL.parseURIEncoded(moduleName), path, JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), JavaHLObjectFactory.getSVNDepth(depth), allowUnverObstructions); } catch (SVNException e) { throwException(e); } finally { updater.setIgnoreExternals(oldIgnoreExternals); resetLog(); } return -1; } public void diff(String target1, Revision revision1, String target2, Revision revision2, String outFileName, boolean recurse) throws ClientException { diff(target1, revision1, target2, revision2, outFileName, recurse, true, false, false); } public void diff(String target1, Revision revision1, String target2, Revision revision2, String outFileName, boolean recurse, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { diff(target1, revision1, target2, revision2, null, outFileName, JavaHLObjectFactory.infinityOrFiles(recurse), null, ignoreAncestry, noDiffDeleted, force); } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String outFileName, boolean recurse, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { diff(target, pegRevision, startRevision, endRevision, null, outFileName, JavaHLObjectFactory.unknownOrFiles(recurse), null, ignoreAncestry, noDiffDeleted, force); } public void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { SVNDiffClient differ = getSVNDiffClient(); differ.getDiffGenerator().setDiffDeleted(!noDiffDeleted); differ.getDiffGenerator().setForcedBinaryDiff(force); differ.setOptions(getOptions()); SVNRevision rev1 = JavaHLObjectFactory.getSVNRevision(revision1); SVNRevision rev2 = JavaHLObjectFactory.getSVNRevision(revision2); try { differ.getDiffGenerator().setBasePath(getDiffBasePath(relativeToDir)); OutputStream out = SVNFileUtil.openFileForWriting(new File(outFileName)); if (!isURL(target1) && !isURL(target2)) { differ.doDiff(new File(target1).getAbsoluteFile(), rev1, new File(target2).getAbsoluteFile(), rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, out, JavaHLObjectFactory.getChangeListsCollection(changelists)); } else if (isURL(target1) && isURL(target2)) { SVNURL url1 = SVNURL.parseURIEncoded(target1); SVNURL url2 = SVNURL.parseURIEncoded(target2); differ.doDiff(url1, rev1, url2, rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, out); } else if (!isURL(target1) && isURL(target2)) { SVNURL url2 = SVNURL.parseURIEncoded(target2); differ.doDiff(new File(target1).getAbsoluteFile(), rev1, url2, rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, out, JavaHLObjectFactory.getChangeListsCollection(changelists)); } else if (isURL(target1) && !isURL(target2)) { SVNURL url1 = SVNURL.parseURIEncoded(target1); differ.doDiff(url1, rev1, new File(target2).getAbsoluteFile(), rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, out, JavaHLObjectFactory.getChangeListsCollection(changelists)); } SVNFileUtil.closeFile(out); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException { SVNDiffClient differ = getSVNDiffClient(); differ.getDiffGenerator().setDiffDeleted(!noDiffDeleted); differ.getDiffGenerator().setForcedBinaryDiff(force); differ.setOptions(getOptions()); SVNRevision peg = JavaHLObjectFactory.getSVNRevision(pegRevision); SVNRevision rev1 = JavaHLObjectFactory.getSVNRevision(startRevision); SVNRevision rev2 = JavaHLObjectFactory.getSVNRevision(endRevision); try { differ.getDiffGenerator().setBasePath(getDiffBasePath(relativeToDir)); OutputStream out = SVNFileUtil.openFileForWriting(new File(outFileName)); if (isURL(target)) { SVNURL url = SVNURL.parseURIEncoded(target); differ.doDiff(url, peg, rev1, rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, out); } else { differ.doDiff(new File(target).getAbsoluteFile(), peg, rev1, rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, out, JavaHLObjectFactory.getChangeListsCollection(changelists)); } SVNFileUtil.closeFile(out); } catch (SVNException e) { throwException(e); } finally { resetLog(); } } private static File getDiffBasePath(String relativePath) throws SVNException { File file = null; if (relativePath != null) { if (isURL(relativePath)) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.BAD_RELATIVE_PATH, "Relative path ''{0}'' should not be URL", relativePath), SVNLogType.DEFAULT); } file = new File(relativePath).getAbsoluteFile(); } return file; } public void diffSummarize(String target1, Revision revision1, String target2, Revision revision2, int depth, String[] changelists, boolean ignoreAncestry, final DiffSummaryReceiver receiver) throws ClientException { SVNDiffClient differ = getSVNDiffClient(); SVNRevision rev1 = JavaHLObjectFactory.getSVNRevision(revision1); SVNRevision rev2 = JavaHLObjectFactory.getSVNRevision(revision2); ISVNDiffStatusHandler handler = new ISVNDiffStatusHandler() { public void handleDiffStatus(SVNDiffStatus diffStatus) throws SVNException { if (receiver != null) { if (diffStatus != null && (diffStatus.isPropertiesModified() || (diffStatus.getModificationType() != SVNStatusType.STATUS_NORMAL && diffStatus.getModificationType() != SVNStatusType.STATUS_NONE))) { receiver.onSummary(JavaHLObjectFactory.createDiffSummary(diffStatus)); } } } }; try { if (!isURL(target1) && !isURL(target2)) { differ.doDiffStatus(new File(target1).getAbsoluteFile(), rev1, new File(target2).getAbsoluteFile(), rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, handler); } else if (isURL(target1) && isURL(target2)) { SVNURL url1 = SVNURL.parseURIEncoded(target1); SVNURL url2 = SVNURL.parseURIEncoded(target2); differ.doDiffStatus(url1, rev1, url2, rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, handler); } else if (!isURL(target1) && isURL(target2)) { SVNURL url2 = SVNURL.parseURIEncoded(target2); differ.doDiffStatus(new File(target1).getAbsoluteFile(), rev1, url2, rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, handler); } else if (isURL(target1) && !isURL(target2)) { SVNURL url1 = SVNURL.parseURIEncoded(target1); differ.doDiffStatus(url1, rev1, new File(target2).getAbsoluteFile(), rev2, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, handler); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public void diffSummarize(String target, Revision pegRevision, Revision startRevision, Revision endRevision, int depth, String[] changelists, boolean ignoreAncestry, final DiffSummaryReceiver receiver) throws ClientException { SVNDiffClient differ = getSVNDiffClient(); SVNRevision rev1 = JavaHLObjectFactory.getSVNRevision(startRevision); SVNRevision rev2 = JavaHLObjectFactory.getSVNRevision(endRevision); SVNRevision pegRev = JavaHLObjectFactory.getSVNRevision(pegRevision); ISVNDiffStatusHandler handler = new ISVNDiffStatusHandler() { public void handleDiffStatus(SVNDiffStatus diffStatus) throws SVNException { if (diffStatus != null && receiver != null) { if (diffStatus.isPropertiesModified() || (diffStatus.getModificationType() != SVNStatusType.STATUS_NORMAL && diffStatus.getModificationType() != SVNStatusType.STATUS_NONE)) { receiver.onSummary(JavaHLObjectFactory.createDiffSummary(diffStatus)); } } } }; try { if (!isURL(target)) { differ.doDiffStatus(new File(target).getAbsoluteFile(), rev1, rev2, pegRev, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, handler); } else { SVNURL url = SVNURL.parseURIEncoded(target); differ.doDiffStatus(url, rev1, rev2, pegRev, JavaHLObjectFactory.getSVNDepth(depth), !ignoreAncestry, handler); } } catch (SVNException e) { throwException(e); } finally { resetLog(); } } public Info2[] info2(String pathOrUrl, Revision revision, Revision pegRevision, boolean recurse) throws ClientException { final Collection infos = new ArrayList(); try { info2(pathOrUrl, revision, pegRevision, JavaHLObjectFactory.infinityOrEmpty(recurse), null, new ISVNInfoHandler() { public void handleInfo(SVNInfo info) { infos.add(JavaHLObjectFactory.createInfo2(info)); } }); return (Info2[]) infos.toArray(new Info2[infos.size()]); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.UNVERSIONED_RESOURCE) { return new Info2[0]; } throwException(e); } finally { resetLog(); } return null; } public void info2(String pathOrUrl, Revision revision, Revision pegRevision, int depth, String[] changelists, InfoCallback callback) throws ClientException { final InfoCallback infoCallback = callback; try { info2(pathOrUrl, revision, pegRevision, depth, changelists, new ISVNInfoHandler() { public void handleInfo(SVNInfo info) { if (infoCallback != null) { infoCallback.singleInfo(JavaHLObjectFactory.createInfo2(info)); } } }); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.UNVERSIONED_RESOURCE) { throwException(e); } } finally { resetLog(); } } private void info2(String pathOrUrl, Revision revision, Revision pegRevision, int depth, String[] changelists, ISVNInfoHandler handler) throws SVNException { SVNWCClient client = getSVNWCClient(); if (isURL(pathOrUrl)) { client.doInfo(SVNURL.parseURIEncoded(pathOrUrl), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), JavaHLObjectFactory.getSVNDepth(depth), handler); } else { Collection changeListsCollection = null; if (changelists != null && changelists.length > 0) { changeListsCollection = Arrays.asList(changelists); } client.doInfo(new File(pathOrUrl).getAbsoluteFile(), JavaHLObjectFactory.getSVNRevision(pegRevision), JavaHLObjectFactory.getSVNRevision(revision), JavaHLObjectFactory.getSVNDepth(depth), changeListsCollection, handler); } } public void logMessages(String path, Revision pegRevision, RevisionRange[] ranges, boolean stopOnCopy, boolean discoverPath, boolean includeMergedRevisions, String[] revProps, long limit, LogMessageCallback callback) throws ClientException { final LogMessageCallback logMessageCallback = callback; for (int i = 0; i < ranges.length; i++) { RevisionRange range = ranges[i]; logMessages(path, pegRevision, range.getFromRevision(), range.getToRevision(), stopOnCopy, discoverPath, includeMergedRevisions, revProps, limit, new ISVNLogEntryHandler() { public void handleLogEntry(SVNLogEntry logEntry) { JavaHLObjectFactory.handleLogMessage(logEntry, logMessageCallback); } } ); } } public void setRevProperty(String path, String name, Revision rev, String value, String originalValue, boolean force) throws ClientException { // TODO use original value. setRevProperty(path, name, rev, value, force); } public void copy(CopySource[] sources, String destPath, String message, boolean copyAsChild, boolean makeParents, boolean ignoreExternals, Map revpropTable) throws ClientException { } public void getMergeinfoLog(int kind, String pathOrUrl, Revision pegRevision, String mergeSourceUrl, Revision srcPegRevision, boolean discoverChangedPaths, int depth, String[] revProps, LogMessageCallback callback) throws ClientException { } public void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, String outFileName, int depth, String[] changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, BlameCallback3 callback) throws ClientException { } public void upgrade(String path) throws ClientException { } } SVNClientImplTracker.java000066400000000000000000000053511177510526000337040ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import java.util.Iterator; import java.util.Map; /** * @version 1.3 * @author TMate Software Ltd. */ public class SVNClientImplTracker implements Runnable { private static ReferenceQueue ourQueue; private static Map ourReferences = new SVNHashMap(); public static void registerClient(SVNClientImpl client) { synchronized (SVNClientImplTracker.class) { if (ourQueue == null) { ourQueue = new ReferenceQueue(); Thread th = new Thread(new SVNClientImplTracker()); th.setDaemon(true); th.start(); } } synchronized (ourReferences) { SVNClientImpl oldClient = null; for (Iterator refs = ourReferences.keySet().iterator(); refs.hasNext();) { WeakReference reference = (WeakReference) refs.next(); if (reference.get() == Thread.currentThread()) { oldClient = (SVNClientImpl) ourReferences.get(reference); if (oldClient != null) { oldClient.dispose(); } refs.remove(); } } WeakReference ref = new WeakReference(Thread.currentThread(), ourQueue); oldClient = (SVNClientImpl) ourReferences.put(ref, client); if (oldClient != null) { oldClient.dispose(); } } } public void run() { while(true) { Reference reference = null; try { reference = ourQueue.remove(); } catch (IllegalArgumentException e) { } catch (InterruptedException e) { } if (reference == null) { continue; } synchronized (ourReferences) { SVNClientImpl oldClient = (SVNClientImpl) ourReferences.remove(reference); if (oldClient != null) { oldClient.dispose(); } } } } } SVNClientImplVersion.java000066400000000000000000000030251177510526000337320ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.javahl; import org.tigris.subversion.javahl.Version; /** * @version 1.3 * @author TMate Software Ltd. */ class SVNClientImplVersion extends org.tigris.subversion.javahl.Version { private static SVNClientImplVersion ourInstance; public int getMajor() { return SVNClientImpl.versionMajor(); } public int getMinor() { return SVNClientImpl.versionMinor(); } public int getPatch() { return SVNClientImpl.versionMicro(); } public long getRevisionNumber() { return SVNClientImpl.versionRevisionNumber(); } public String toString() { String revision = getRevisionNumber() < 0 ? "SNAPSHOT" : Long.toString(getRevisionNumber()); return "SVNKit v" + getMajor() + "." + getMinor() + "." + getPatch() + "." + revision; } public static Version getInstance() { if (ourInstance == null) { ourInstance = new SVNClientImplVersion(); } return ourInstance; } }svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl/package.html000066400000000000000000000017161177510526000314370ustar00rootroot00000000000000 package org.tmatesoft.svn.core.io

This package provides an implementation of the native Subversion javahl binding interface SVNClientInterface that is distributed within the org.tigris.subversion.javahl package. This implementation - called SVNClientImpl - is a replacement for the Subversion's default one - SVNClient (also distributed in org.tigris.subversion.javahl). The main difference between these implementations concludes in that the native javahl binding class SVNClient uses system dependent native libraries (in most cases a user need to build those libraries by himself) while SVNKit solution - SVNClientImpl - uses the SVNKit library itself which is an absolutely pure Java client library that has no native dependancies.

svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17/000077500000000000000000000000001177510526000273215ustar00rootroot00000000000000JavaHLAuthenticationProvider.java000066400000000000000000000232631177510526000356330ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17package org.tmatesoft.svn.core.javahl17; import java.io.File; import java.security.cert.X509Certificate; import java.text.MessageFormat; import org.apache.subversion.javahl.callback.UserPasswordCallback; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.auth.SVNSSHAuthentication; import org.tmatesoft.svn.core.auth.SVNSSLAuthentication; import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication; import org.tmatesoft.svn.core.internal.util.SVNSSLUtil; import org.tmatesoft.svn.core.internal.wc.ISVNSSLPasspharsePromptSupport; class JavaHLAuthenticationProvider implements ISVNAuthenticationProvider, ISVNSSLPasspharsePromptSupport { //TODO: what is the constant about? private static final String ADAPTER_DEFAULT_PROMPT_CLASS = "org.tigris.subversion.svnclientadapter.javahl.AbstractJhlClientAdapter$DefaultPromptUserPassword"; private UserPasswordCallback prompt; public JavaHLAuthenticationProvider(UserPasswordCallback prompt){ this.prompt = prompt; } public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) { if (ISVNAuthenticationManager.SSH.equals(kind) && prompt instanceof UserPasswordSSHCallback) { UserPasswordSSHCallback prompt4 = (UserPasswordSSHCallback) prompt; String userName = previousAuth != null && previousAuth.getUserName() != null ? previousAuth.getUserName() : getUserName(null, url); int port = url != null ? url.getPort() : -1; if (prompt4.promptSSH(realm, userName, port, authMayBeStored)) { String password = prompt4.getPassword(); String keyPath = prompt4.getSSHPrivateKeyPath(); String passphrase = prompt4.getSSHPrivateKeyPassphrase(); userName = getUserName(prompt4.getUsername(), url); if ("".equals(passphrase)) { passphrase = null; } port = prompt4.getSSHPort(); if (port < 0 && url != null) { port = url.getPort(); } if (port < 0) { port = 22; } boolean save = prompt4.userAllowedSave(); if (keyPath != null && !"".equals(keyPath)) { return new SVNSSHAuthentication(userName, new File(keyPath), passphrase, port, save, url, false); } else if (password != null){ return new SVNSSHAuthentication(userName, password, port, save, url, false); } } return null; } else if (ISVNAuthenticationManager.SSL.equals(kind) && SVNSSLAuthentication.isCertificatePath(realm)) { String passphrase = prompt.askQuestion(realm, "SSL Certificate Passphrase", authMayBeStored); if (passphrase != null) { return new SVNPasswordAuthentication("", passphrase, prompt.userAllowedSave(), url, false); } } else if (ISVNAuthenticationManager.SSL.equals(kind) && !SVNSSLAuthentication.isCertificatePath(realm) && (prompt instanceof UserPasswordSSLCallback)) { UserPasswordSSLCallback prompt4 = (UserPasswordSSLCallback) prompt; if (prompt4.promptSSL(realm, authMayBeStored)) { String cert = prompt4.getSSLClientCertPath(); String password = prompt4.getSSLClientCertPassword(); if (cert != null) { if ("".equals(password)) { password = null; } boolean save = prompt.userAllowedSave(); if (cert.startsWith(SVNSSLAuthentication.MSCAPI)) { String alias = null; if (cert.lastIndexOf(';') > 0) { alias = cert.substring(cert.lastIndexOf(';') + 1); } return new SVNSSLAuthentication(SVNSSLAuthentication.MSCAPI, alias, save, url, false); } SVNSSLAuthentication sslAuth = new SVNSSLAuthentication(new File(cert), password, save, url, false); sslAuth.setCertificatePath(cert); return sslAuth; } } return null; } if (ISVNAuthenticationManager.SSH.equals(kind) && previousAuth == null) { // use configuration file here? but it was already used once... String keyPath = System.getProperty("svnkit.ssh2.key", System.getProperty("javasvn.ssh2.key")); String userName = getUserName(System.getProperty("svnkit.ssh2.username", System.getProperty("javasvn.ssh2.username")), url); String passPhrase = System.getProperty("svnkit.ssh2.passphrase", System.getProperty("javasvn.ssh2.passphrase")); if (userName == null) { return null; } if (keyPath != null && previousAuth == null) { // use port number from configuration file? return new SVNSSHAuthentication(userName, new File(keyPath), passPhrase, -1, true, url, false); } // try to get password for ssh from the user. } else if(ISVNAuthenticationManager.USERNAME.equals(kind)) { String userName = previousAuth != null && previousAuth.getUserName() != null ? previousAuth.getUserName() : getUserName(null, url); if (prompt.prompt(realm, userName, authMayBeStored)) { return new SVNUserNameAuthentication(prompt.getUsername(), prompt.userAllowedSave(), url, false); } return getDefaultUserNameCredentials(userName); //TODO: prompt.prompt(String, String) is not used // if (prompt.prompt(realm, userName)) { // return new SVNUserNameAuthentication(prompt.getUsername(), false, url, false); // } // return getDefaultUserNameCredentials(userName); } else if(!ISVNAuthenticationManager.PASSWORD.equals(kind)){ return null; } String userName = previousAuth != null && previousAuth.getUserName() != null ? previousAuth.getUserName() : getUserName(null, url); // if (prompt instanceof PromptUserPassword3) { if(prompt.prompt(realm, userName, authMayBeStored)){ if (ISVNAuthenticationManager.SSH.equals(kind)) { // use default port number from configuration file (should be in previous auth). int portNumber = (previousAuth instanceof SVNSSHAuthentication) ? ((SVNSSHAuthentication) previousAuth).getPortNumber() : -1; return new SVNSSHAuthentication(prompt.getUsername(), prompt.getPassword(), portNumber, prompt.userAllowedSave(), url, false); } return new SVNPasswordAuthentication(prompt.getUsername(), prompt.getPassword(), prompt.userAllowedSave(), url, false); } //TODO: prompt.prompt(String, String) is not used // }else{ // if(prompt.prompt(realm, userName)){ // if (ISVNAuthenticationManager.SSH.equals(kind)) { // return new SVNSSHAuthentication(userName, prompt.getPassword(), -1, true, url, false); // } // return new SVNPasswordAuthentication(prompt.getUsername(), prompt.getPassword(), true, url, false); // } // } return null; } private SVNAuthentication getDefaultUserNameCredentials(String userName) { if (ADAPTER_DEFAULT_PROMPT_CLASS.equals(prompt.getClass().getName())) { // return default username, despite prompt was 'cancelled'. return new SVNUserNameAuthentication(userName, false, null, false); } return null; } public int acceptServerAuthentication(SVNURL url, String realm, Object serverAuth, boolean resultMayBeStored) { if (serverAuth instanceof X509Certificate) { serverAuth = serverAuth instanceof X509Certificate ? SVNSSLUtil.getServerCertificatePrompt((X509Certificate) serverAuth, realm, url.getHost()) : serverAuth; if (serverAuth == null) { serverAuth = "Unsupported certificate type '" + (serverAuth != null ? serverAuth.getClass().getName() : "null") + "'"; } return prompt.askTrustSSLServer(serverAuth.toString(), resultMayBeStored); } else if (prompt != null && serverAuth instanceof byte[]) { String prompt = "The ''{0}'' server''s key fingerprint is:\n{1}\n" + "If you trust this host, select ''Yes'' to add the key to the SVN cache and carry on connecting.\n" + "If you do not trust this host, select ''No'' to abandon the connection."; prompt = MessageFormat.format(prompt, new Object[]{url.getHost(), SVNSSLUtil.getFingerprint((byte[]) serverAuth, "MD5")}); if (!this.prompt.askYesNo(realm, prompt, false)) { return REJECTED; } } return ACCEPTED; } public boolean isSSLPassphrasePromtSupported() { return true; } private static String getUserName(String userName, SVNURL url) { if (userName == null || "".equals(userName.trim())) { userName = url != null ? url.getUserInfo() : null; } if (userName == null || "".equals(userName.trim())) { userName = System.getProperty("user.name"); } return userName; } } JavaHLAuthenticationStorage.java000066400000000000000000000011501177510526000354340ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17package org.tmatesoft.svn.core.javahl17; import java.util.Hashtable; import java.util.Map; import org.tmatesoft.svn.core.internal.wc.ISVNAuthenticationStorage; public class JavaHLAuthenticationStorage implements ISVNAuthenticationStorage { private Map myStorage = new Hashtable(); public void putData(String kind, String realm, Object data) { myStorage.put(kind + "$" + realm, data); } public Object getData(String kind, String realm) { return myStorage.get(kind + "$" + realm); } public void clear() { myStorage.clear(); } } JavaHLEventHandler.java000066400000000000000000000043411177510526000335140ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17package org.tmatesoft.svn.core.javahl17; import java.io.File; import org.apache.subversion.javahl.ClientNotifyInformation; import org.apache.subversion.javahl.callback.ClientNotifyCallback; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.util.SVNLogType; public class JavaHLEventHandler implements ISVNEventHandler { private ClientNotifyCallback notifyCallback; private boolean cancelOperation; private String pathPrefix; public JavaHLEventHandler() { this.cancelOperation = false; resetPathPrefix(); } public void setNotifyCallback(ClientNotifyCallback notifyCallback) { this.notifyCallback = notifyCallback; } public void setCancelOperation(boolean cancelOperation) { this.cancelOperation = cancelOperation; } public void cancelOperation() { setCancelOperation(true); } public void setPathPrefix(String pathPrefix) { this.pathPrefix = pathPrefix; } public void resetPathPrefix() { setPathPrefix(null); } public void handleEvent(SVNEvent event, double progress) { if (event.getAction() == SVNEventAction.UPGRADE) { return; } String path = null; if (event.getFile() != null) { path = event.getFile().getAbsolutePath(); if (path != null) { path = path.replace(File.separatorChar, '/'); } } if (path == null) { path = ""; } if (notifyCallback != null) { String pathPrefix = this.pathPrefix == null ? "" : this.pathPrefix; ClientNotifyInformation ni = SVNClientImpl.getClientNotifyInformation(pathPrefix, event, path); if (ni != null) { notifyCallback.onNotify(ni); } } } public void checkCancelled() throws SVNCancelException { if (cancelOperation) { cancelOperation = false; SVNErrorManager.cancel("operation cancelled", SVNLogType.DEFAULT); } } } JavaHLProgressLog.java000066400000000000000000000020611177510526000334000ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17package org.tmatesoft.svn.core.javahl17; import java.util.logging.Level; import org.apache.subversion.javahl.ProgressEvent; import org.apache.subversion.javahl.callback.ProgressCallback; import org.tmatesoft.svn.util.SVNDebugLogAdapter; import org.tmatesoft.svn.util.SVNLogType; public class JavaHLProgressLog extends SVNDebugLogAdapter { private ProgressCallback progressCallback; private long progress; public JavaHLProgressLog(ProgressCallback progressCallback) { this.progressCallback = progressCallback; reset(); } public void log(SVNLogType logType, String message, byte[] data) { progress += data.length; progressCallback.onProgress(createProgressEvent(progress)); } public void reset() { progress = 0; } public void log(SVNLogType logType, Throwable th, Level logLevel) { } public void log(SVNLogType logType, String message, Level logLevel) { } private ProgressEvent createProgressEvent(long progress) { return new ProgressEvent(progress, -1L); } } svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17/SVNClientImpl.java000066400000000000000000003345731177510526000326320ustar00rootroot00000000000000package org.tmatesoft.svn.core.javahl17; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.subversion.javahl.ClientException; import org.apache.subversion.javahl.ClientNotifyInformation; import org.apache.subversion.javahl.CommitInfo; import org.apache.subversion.javahl.CommitItem; import org.apache.subversion.javahl.ConflictDescriptor; import org.apache.subversion.javahl.ConflictDescriptor.Operation; import org.apache.subversion.javahl.ConflictResult; import org.apache.subversion.javahl.ConflictResult.Choice; import org.apache.subversion.javahl.DiffSummary; import org.apache.subversion.javahl.ISVNClient; import org.apache.subversion.javahl.SubversionException; import org.apache.subversion.javahl.callback.BlameCallback; import org.apache.subversion.javahl.callback.ChangelistCallback; import org.apache.subversion.javahl.callback.ClientNotifyCallback; import org.apache.subversion.javahl.callback.CommitCallback; import org.apache.subversion.javahl.callback.CommitMessageCallback; import org.apache.subversion.javahl.callback.ConflictResolverCallback; import org.apache.subversion.javahl.callback.DiffSummaryCallback; import org.apache.subversion.javahl.callback.InfoCallback; import org.apache.subversion.javahl.callback.ListCallback; import org.apache.subversion.javahl.callback.LogMessageCallback; import org.apache.subversion.javahl.callback.PatchCallback; import org.apache.subversion.javahl.callback.ProgressCallback; import org.apache.subversion.javahl.callback.ProplistCallback; import org.apache.subversion.javahl.callback.StatusCallback; import org.apache.subversion.javahl.callback.UserPasswordCallback; import org.apache.subversion.javahl.types.ChangePath; import org.apache.subversion.javahl.types.Checksum; import org.apache.subversion.javahl.types.ConflictVersion; import org.apache.subversion.javahl.types.CopySource; import org.apache.subversion.javahl.types.Depth; import org.apache.subversion.javahl.types.DirEntry; import org.apache.subversion.javahl.types.Info; import org.apache.subversion.javahl.types.Lock; import org.apache.subversion.javahl.types.Mergeinfo; import org.apache.subversion.javahl.types.Mergeinfo.LogKind; import org.apache.subversion.javahl.types.NodeKind; import org.apache.subversion.javahl.types.Revision; import org.apache.subversion.javahl.types.RevisionRange; import org.apache.subversion.javahl.types.Status; import org.apache.subversion.javahl.types.Tristate; import org.apache.subversion.javahl.types.Version; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.SVNLogEntryPath; import org.tmatesoft.svn.core.SVNMergeRange; import org.tmatesoft.svn.core.SVNMergeRangeList; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.io.svn.SVNSSHConnector; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.ISVNAuthenticationStorage; import org.tmatesoft.svn.core.internal.wc.SVNConflictVersion; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.patch.SVNPatchHunkInfo; import org.tmatesoft.svn.core.javahl.JavaHLCompositeLog; import org.tmatesoft.svn.core.javahl.JavaHLDebugLog; import org.tmatesoft.svn.core.wc.ISVNConflictHandler; import org.tmatesoft.svn.core.wc.ISVNOptions; import org.tmatesoft.svn.core.wc.SVNConflictAction; import org.tmatesoft.svn.core.wc.SVNConflictChoice; import org.tmatesoft.svn.core.wc.SVNConflictDescription; import org.tmatesoft.svn.core.wc.SVNConflictReason; import org.tmatesoft.svn.core.wc.SVNConflictResult; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc.SVNOperation; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNTreeConflictDescription; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.core.wc2.ISvnObjectReceiver; import org.tmatesoft.svn.core.wc2.SvnAnnotate; import org.tmatesoft.svn.core.wc2.SvnAnnotateItem; import org.tmatesoft.svn.core.wc2.SvnCat; import org.tmatesoft.svn.core.wc2.SvnCheckout; import org.tmatesoft.svn.core.wc2.SvnChecksum; import org.tmatesoft.svn.core.wc2.SvnCleanup; import org.tmatesoft.svn.core.wc2.SvnCommit; import org.tmatesoft.svn.core.wc2.SvnCommitItem; import org.tmatesoft.svn.core.wc2.SvnCopy; import org.tmatesoft.svn.core.wc2.SvnCopySource; import org.tmatesoft.svn.core.wc2.SvnDiff; import org.tmatesoft.svn.core.wc2.SvnDiffStatus; import org.tmatesoft.svn.core.wc2.SvnDiffSummarize; import org.tmatesoft.svn.core.wc2.SvnExport; import org.tmatesoft.svn.core.wc2.SvnGetInfo; import org.tmatesoft.svn.core.wc2.SvnGetMergeInfo; import org.tmatesoft.svn.core.wc2.SvnGetProperties; import org.tmatesoft.svn.core.wc2.SvnGetStatus; import org.tmatesoft.svn.core.wc2.SvnGetStatusSummary; import org.tmatesoft.svn.core.wc2.SvnImport; import org.tmatesoft.svn.core.wc2.SvnInfo; import org.tmatesoft.svn.core.wc2.SvnList; import org.tmatesoft.svn.core.wc2.SvnLog; import org.tmatesoft.svn.core.wc2.SvnLogMergeInfo; import org.tmatesoft.svn.core.wc2.SvnMerge; import org.tmatesoft.svn.core.wc2.SvnOperationFactory; import org.tmatesoft.svn.core.wc2.SvnRelocate; import org.tmatesoft.svn.core.wc2.SvnRemoteCopy; import org.tmatesoft.svn.core.wc2.SvnRemoteDelete; import org.tmatesoft.svn.core.wc2.SvnRemoteMkDir; import org.tmatesoft.svn.core.wc2.SvnRemoteSetProperty; import org.tmatesoft.svn.core.wc2.SvnResolve; import org.tmatesoft.svn.core.wc2.SvnRevert; import org.tmatesoft.svn.core.wc2.SvnRevisionRange; import org.tmatesoft.svn.core.wc2.SvnSchedule; import org.tmatesoft.svn.core.wc2.SvnScheduleForAddition; import org.tmatesoft.svn.core.wc2.SvnScheduleForRemoval; import org.tmatesoft.svn.core.wc2.SvnSetChangelist; import org.tmatesoft.svn.core.wc2.SvnSetLock; import org.tmatesoft.svn.core.wc2.SvnSetProperty; import org.tmatesoft.svn.core.wc2.SvnStatus; import org.tmatesoft.svn.core.wc2.SvnStatusSummary; import org.tmatesoft.svn.core.wc2.SvnSuggestMergeSources; import org.tmatesoft.svn.core.wc2.SvnSwitch; import org.tmatesoft.svn.core.wc2.SvnTarget; import org.tmatesoft.svn.core.wc2.SvnUnlock; import org.tmatesoft.svn.core.wc2.SvnUpdate; import org.tmatesoft.svn.core.wc2.SvnUpgrade; import org.tmatesoft.svn.core.wc2.SvnWorkingCopyInfo; import org.tmatesoft.svn.core.wc2.hooks.ISvnCommitHandler; import org.tmatesoft.svn.util.ISVNDebugLog; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; public class SVNClientImpl implements ISVNClient { private static final String APR_ERROR_FIELD_NAME = "aprError"; public static SVNClientImpl newInstance() { return new SVNClientImpl(); } private static int instanceCount; private SvnOperationFactory svnOperationFactory; private boolean shouldDisposeSvnOperationsFactory; private String username; private String password; private UserPasswordCallback prompt; private String configDir; private DefaultSVNOptions options; private ISVNAuthenticationManager authenticationManager; private ISVNAuthenticationStorage authenticationStorage; private ISVNConflictHandler conflictHandler; private JavaHLEventHandler eventHandler; private JavaHLCompositeLog debugLog; private JavaHLProgressLog progressListener; private static ISVNAuthenticationStorage runtimeAuthenticationStorage; private ConflictResolverCallback conflictResolverCallback; protected SVNClientImpl() { this(null); } protected SVNClientImpl(SvnOperationFactory svnOperationFactory) { this.configDir = SVNWCUtil.getDefaultConfigurationDirectory().getAbsolutePath(); this.shouldDisposeSvnOperationsFactory = svnOperationFactory == null; this.svnOperationFactory = svnOperationFactory == null ? new SvnOperationFactory() : svnOperationFactory; this.svnOperationFactory.setEventHandler(getEventHandler()); synchronized (SVNClientImpl.class) { instanceCount++; } } public void dispose() { if (shouldDisposeSvnOperationsFactory && svnOperationFactory != null) { svnOperationFactory.dispose(); } synchronized (SVNClientImpl.class) { instanceCount--; if (instanceCount <= 0) { instanceCount = 0; SVNSSHConnector.shutdown(); } } } public Version getVersion() { return SVNClientImplVersion.getInstance(); } public String getAdminDirectoryName() { return SVNFileUtil.getAdminDirectoryName(); } public boolean isAdminDirectory(String name) { return name != null && (SVNFileUtil.isWindows) ? SVNFileUtil.getAdminDirectoryName().equalsIgnoreCase(name) : SVNFileUtil.getAdminDirectoryName().equals(name); } public ISVNOptions getOptions() { if (options == null) { File configDir = this.configDir == null ? null : new File(this.configDir); options = SVNWCUtil.createDefaultOptions(configDir, true); options.setConflictHandler(getConflictHandler()); } return options; } protected ISVNConflictHandler getConflictHandler() { if (conflictHandler == null && conflictResolverCallback != null) { conflictHandler = getConflictHandler(conflictResolverCallback); } return conflictHandler; } public void status(String path, Depth depth, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals, Collection changelists, final StatusCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnGetStatus status = svnOperationFactory.createGetStatus(); status.setDepth(getSVNDepth(depth)); status.setRemote(onServer); status.setReportAll(getAll); status.setReportIgnored(noIgnore); status.setReportExternals(!ignoreExternals); status.setApplicalbeChangelists(changelists); status.setReceiver(getStatusReceiver(callback)); status.addTarget(getTarget(path)); status.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void list(String url, Revision revision, Revision pegRevision, Depth depth, int direntFields, boolean fetchLocks, ListCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(url)); SvnList list = svnOperationFactory.createList(); list.setSingleTarget(getTarget(url, pegRevision)); list.setRevision(getSVNRevision(revision)); list.setDepth(getSVNDepth(depth)); list.setEntryFields(direntFields); list.setFetchLocks(fetchLocks); list.setReceiver(getDirEntryReceiver(callback)); list.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void username(String username) { this.username = username; updateSvnOperationsFactory(); } public void password(String password) { this.password = password; updateSvnOperationsFactory(); } public void setPrompt(UserPasswordCallback prompt) { this.prompt = prompt; updateSvnOperationsFactory(); } public void logMessages(String path, Revision pegRevision, List ranges, boolean stopOnCopy, boolean discoverPath, boolean includeMergedRevisions, Set revProps, long limit, LogMessageCallback callback) throws ClientException { beforeOperation(); if (ranges != null) { List filteredRanges = new ArrayList(ranges.size()); for (RevisionRange range : ranges) { RevisionRange filteredRange; if (range.getFromRevision() == null && range.getToRevision() == null) { filteredRange = new RevisionRange(new Revision.Number(1), Revision.HEAD); } else { filteredRange = range; } filteredRanges.add(filteredRange); } ranges = filteredRanges; } try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnLog log = svnOperationFactory.createLog(); log.setRevisionRanges(getSvnRevisionRanges(ranges)); log.setStopOnCopy(stopOnCopy); log.setDiscoverChangedPaths(discoverPath); log.setUseMergeHistory(includeMergedRevisions); log.setRevisionProperties(getRevisionPropertiesNames(revProps)); log.setLimit(limit); log.setReceiver(getLogEntryReceiver(callback)); log.addTarget(getTarget(path, pegRevision)); log.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, Depth depth, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(destPath)); SvnCheckout checkout = svnOperationFactory.createCheckout(); checkout.setSource(getTarget(moduleName, pegRevision)); checkout.setSingleTarget(getTarget(destPath)); checkout.setRevision(getSVNRevision(revision)); checkout.setDepth(getSVNDepth(depth)); checkout.setIgnoreExternals(ignoreExternals); checkout.setAllowUnversionedObstructions(allowUnverObstructions); return checkout.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void notification2(ClientNotifyCallback notifyCallback) { getEventHandler().setNotifyCallback(notifyCallback); } public JavaHLEventHandler getEventHandler() { if (eventHandler == null) { eventHandler = new JavaHLEventHandler(); } return eventHandler; } public void setConflictResolver(final ConflictResolverCallback callback) { conflictResolverCallback = callback; conflictHandler = callback != null ? new ISVNConflictHandler() { public SVNConflictResult handleConflict(SVNConflictDescription conflictDescription) throws SVNException { ConflictResult result = null; try { result = callback.resolve(getConflictDescription(conflictDescription)); } catch (ClientException e) { throwSvnException(e); } catch (SubversionException e) { throwSvnException(e); } return result != null ? getSVNConflictResult(result) : null; } } : null; updateSvnOperationsFactory(); } public void setProgressCallback(ProgressCallback listener) { getDebugLog();//make sure debugLog is constructed if (listener != null) { progressListener = new JavaHLProgressLog(listener); debugLog.addLogger(progressListener); } else if (progressListener != null) { debugLog.removeLogger(progressListener); progressListener = null; } } public ISVNDebugLog getDebugLog() { if (debugLog == null) { debugLog = new JavaHLCompositeLog(); debugLog.addLogger(SVNDebugLog.getDefaultLog()); debugLog.addLogger(JavaHLDebugLog.getInstance()); } return debugLog; } public void setClientCredentialsStorage(ISVNAuthenticationStorage storage) { authenticationStorage = storage; updateSvnOperationsFactory(); } public ISVNAuthenticationStorage getClientCredentialsStorage() { if (authenticationStorage != null) { return authenticationStorage; } return getRuntimeCredentialsStorage(); } public static void setRuntimeCredentialsStorage(ISVNAuthenticationStorage storage) { synchronized (SVNClientImpl.class) { runtimeAuthenticationStorage = storage == null ? new JavaHLAuthenticationStorage() : storage; } } public static ISVNAuthenticationStorage getRuntimeCredentialsStorage() { synchronized (SVNClientImpl.class) { if (runtimeAuthenticationStorage == null) { runtimeAuthenticationStorage = new JavaHLAuthenticationStorage(); } return runtimeAuthenticationStorage; } } public void remove(Set path, boolean force, boolean keepLocal, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); Set localPaths = new HashSet(); Set remoteUrls = new HashSet(); fillLocalAndRemoteTargets(path, localPaths, remoteUrls); removeLocal(localPaths, force, keepLocal); removeRemote(remoteUrls, revpropTable, handler, callback); } finally { afterOperation(); } } public void revert(String path, Depth depth, Collection changelists) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnRevert revert = svnOperationFactory.createRevert(); revert.setDepth(getSVNDepth(depth)); revert.setApplicalbeChangelists(changelists); revert.addTarget(getTarget(path)); revert.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void add(String path, Depth depth, boolean force, boolean noIgnores, boolean addParents) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnScheduleForAddition add = svnOperationFactory.createScheduleForAddition(); add.setDepth(getSVNDepth(depth)); add.setForce(force); add.setIncludeIgnored(noIgnores); add.setAddParents(addParents); add.addTarget(getTarget(path)); add.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public long[] update(Set path, Revision revision, Depth depth, boolean depthIsSticky, boolean makeParents, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnUpdate update = svnOperationFactory.createUpdate(); update.setRevision(getSVNRevision(revision)); update.setDepth(getSVNDepth(depth)); update.setDepthIsSticky(depthIsSticky); update.setMakeParents(makeParents); update.setIgnoreExternals(ignoreExternals); update.setAllowUnversionedObstructions(allowUnverObstructions); for (String targetPath : path) { update.addTarget(getTarget(targetPath)); } return update.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void commit(Set path, Depth depth, boolean noUnlock, boolean keepChangelist, Collection changelists, Map revpropTable, final CommitMessageCallback handler, CommitCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnCommit commit = svnOperationFactory.createCommit(); commit.setDepth(getSVNDepth(depth)); commit.setKeepLocks(!noUnlock); commit.setKeepChangelists(keepChangelist); commit.setApplicalbeChangelists(changelists); commit.setRevisionProperties(getSVNProperties(revpropTable)); commit.setCommitHandler(getCommitHandler(handler)); commit.setReceiver(getCommitInfoReceiver(callback)); for (String targetPath : path) { commit.addTarget(getTarget(targetPath)); } commit.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void copy(List sources, String destPath, boolean copyAsChild, boolean makeParents, boolean ignoreExternals, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(sources, destPath)); if (SVNPathUtil.isURL(destPath)) { copyRemote(sources, destPath, copyAsChild, makeParents, revpropTable, handler, callback); } else { copyLocal(sources, destPath, copyAsChild, makeParents, ignoreExternals); } } finally { afterOperation(); } } public void move(Set srcPaths, String destPath, boolean force, boolean moveAsChild, boolean makeParents, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(srcPaths, destPath)); if (SVNPathUtil.isURL(destPath)) { moveRemote(srcPaths, destPath, moveAsChild, makeParents, revpropTable, handler, callback); } else { moveLocal(srcPaths, destPath, force, moveAsChild, makeParents); } } finally { afterOperation(); } } public void mkdir(Set path, boolean makeParents, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); final Set localPaths = new HashSet(); final Set remoteUrls = new HashSet(); fillLocalAndRemoteTargets(path, localPaths, remoteUrls); mkdirLocal(localPaths, makeParents); mkdirRemote(remoteUrls, makeParents, revpropTable, handler, callback); } finally { afterOperation(); } } public void cleanup(String path) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnCleanup cleanup = svnOperationFactory.createCleanup(); cleanup.addTarget(getTarget(path)); cleanup.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void resolve(String path, Depth depth, Choice conflictResult) throws SubversionException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnResolve resolve = svnOperationFactory.createResolve(); resolve.setDepth(getSVNDepth(depth)); resolve.setConflictChoice(getSVNConflictChoice(conflictResult)); resolve.addTarget(getTarget(path)); resolve.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, Depth depth, String nativeEOL) throws ClientException { beforeOperation(); try { getPathPrefix(srcPath, destPath); SvnExport export = svnOperationFactory.createExport(); export.setSource(getTarget(srcPath, pegRevision)); export.setSingleTarget(getTarget(destPath)); export.setRevision(getSVNRevision(revision)); export.setForce(force); export.setIgnoreExternals(ignoreExternals); export.setDepth(getSVNDepth(depth)); export.setEolStyle(nativeEOL); return export.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public long doSwitch(String path, String url, Revision revision, Revision pegRevision, Depth depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions, boolean ignoreAncestry) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnSwitch svnSwitch = svnOperationFactory.createSwitch(); svnSwitch.setSingleTarget(getTarget(path)); svnSwitch.setSwitchTarget(getTarget(url, pegRevision)); svnSwitch.setRevision(getSVNRevision(revision)); svnSwitch.setDepth(getSVNDepth(depth)); svnSwitch.setDepthIsSticky(depthIsSticky); svnSwitch.setIgnoreExternals(ignoreExternals); svnSwitch.setAllowUnversionedObstructions(allowUnverObstructions); svnSwitch.setIgnoreAncestry(ignoreAncestry); return svnSwitch.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void doImport(String path, String url, Depth depth, boolean noIgnore, boolean ignoreUnknownNodeTypes, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { beforeOperation(); try{ getEventHandler().setPathPrefix(getPathPrefix(path)); SvnImport svnImport = svnOperationFactory.createImport(); svnImport.setDepth(getSVNDepth(depth)); svnImport.setUseGlobalIgnores(!noIgnore); svnImport.setForce(ignoreUnknownNodeTypes); svnImport.setRevisionProperties(getSVNProperties(revpropTable)); svnImport.setCommitHandler(getCommitHandler(handler)); svnImport.setReceiver(getCommitInfoReceiver(callback)); svnImport.setSource(new File(path)); svnImport.addTarget(getTarget(url)); svnImport.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public Set suggestMergeSources(String path, Revision pegRevision) throws SubversionException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnSuggestMergeSources suggestMergeSources = svnOperationFactory.createSuggestMergeSources(); suggestMergeSources.setSingleTarget(getTarget(path, pegRevision)); Collection mergeSources; mergeSources = suggestMergeSources.run(); Set mergeSourcesStrings = new HashSet(); for (SVNURL mergeSource : mergeSources) { mergeSourcesStrings.add(getUrlString(mergeSource)); } return mergeSourcesStrings; } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, Depth depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path1, path2)); SvnMerge merge = svnOperationFactory.createMerge(); merge.setSources(getTarget(path1, revision1), getTarget(path2, revision2)); merge.addTarget(getTarget(localPath)); merge.setForce(force); merge.setDepth(getSVNDepth(depth)); merge.setIgnoreAncestry(ignoreAncestry); merge.setDryRun(dryRun); merge.setRecordOnly(recordOnly); merge.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void merge(String path, Revision pegRevision, List revisions, String localPath, boolean force, Depth depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path, localPath)); SvnMerge merge = svnOperationFactory.createMerge(); merge.setSource(getTarget(path, pegRevision), false/*reintegrate=false*/); for (RevisionRange revisionRange : revisions) { merge.addRevisionRange(getSvnRevisionRange(revisionRange)); } merge.addTarget(getTarget(localPath)); merge.setForce(force); merge.setDepth(getSVNDepth(depth)); merge.setIgnoreAncestry(ignoreAncestry); merge.setDryRun(dryRun); merge.setRecordOnly(recordOnly); merge.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void mergeReintegrate(String path, Revision pegRevision, String localPath, boolean dryRun) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnMerge merge = svnOperationFactory.createMerge(); merge.setSource(getTarget(path, pegRevision), true/*reintegrate=true*/); merge.addTarget(getTarget(localPath)); merge.setDryRun(dryRun); merge.run(); } catch (SVNException e) { throw SVNClientImpl.getClientException(e); } finally { afterOperation(); } } public Mergeinfo getMergeinfo(String path, Revision pegRevision) throws SubversionException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnGetMergeInfo getMergeInfo = svnOperationFactory.createGetMergeInfo(); getMergeInfo.setSingleTarget(getTarget(path, pegRevision)); return getMergeinfo(getMergeInfo.run()); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void getMergeinfoLog(LogKind kind, String pathOrUrl, Revision pegRevision, String mergeSourceUrl, Revision srcPegRevision, boolean discoverChangedPaths, Depth depth, Set revProps, LogMessageCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(pathOrUrl, mergeSourceUrl)); SvnLogMergeInfo logMergeInfo = svnOperationFactory.createLogMergeInfo(); logMergeInfo.setFindMerged(kind == LogKind.merged); logMergeInfo.setSingleTarget(getTarget(pathOrUrl, pegRevision)); logMergeInfo.setSource(getTarget(mergeSourceUrl, srcPegRevision)); logMergeInfo.setDiscoverChangedPaths(discoverChangedPaths); logMergeInfo.setDepth(getSVNDepth(depth)); logMergeInfo.setRevisionProperties(getRevisionPropertiesNames(revProps)); logMergeInfo.setReceiver(getLogEntryReceiver(callback)); logMergeInfo.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, String outFileName, Depth depth, Collection changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { beforeOperation(); FileOutputStream fileOutputStream = null; BufferedOutputStream bufferedOutputStream = null; try { getEventHandler().setPathPrefix(getPathPrefix(relativeToDir));//TODO: review fileOutputStream = new FileOutputStream(outFileName); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); SvnDiff diff = svnOperationFactory.createDiff(); diff.setSources(getTarget(target1, revision1), getTarget(target2, revision2)); diff.setRelativeToDirectory(getFile(relativeToDir)); diff.setOutput(bufferedOutputStream); diff.setDepth(getSVNDepth(depth)); diff.setApplicalbeChangelists(changelists); diff.setIgnoreAncestry(ignoreAncestry); diff.setNoDiffDeleted(noDiffDeleted); diff.setIgnoreContentType(force); diff.setShowCopiesAsAdds(copiesAsAdds); diff.run(); } catch (FileNotFoundException e) { throw SVNClientImpl.getClientException(e); } catch (SVNException e) { throw getClientException(e); } finally { SVNFileUtil.closeFile(fileOutputStream); SVNFileUtil.closeFile(bufferedOutputStream); afterOperation(); } } public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, String outFileName, Depth depth, Collection changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { beforeOperation(); FileOutputStream fileOutputStream = null; BufferedOutputStream bufferedOutputStream = null; try { getEventHandler().setPathPrefix(getPathPrefix(relativeToDir)); //TODO: review fileOutputStream = new FileOutputStream(outFileName); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); SvnDiff diff = svnOperationFactory.createDiff(); diff.setSource(getTarget(target, pegRevision), getSVNRevision(startRevision), getSVNRevision(endRevision)); diff.setRelativeToDirectory(getFile(relativeToDir)); diff.setOutput(bufferedOutputStream); diff.setDepth(getSVNDepth(depth)); diff.setApplicalbeChangelists(changelists); diff.setIgnoreAncestry(ignoreAncestry); diff.setNoDiffDeleted(noDiffDeleted); diff.setIgnoreContentType(force); diff.setShowCopiesAsAdds(copiesAsAdds); diff.run(); } catch (FileNotFoundException e) { throw SVNClientImpl.getClientException(e); } catch (SVNException e) { throw getClientException(e); } finally { SVNFileUtil.closeFile(fileOutputStream); SVNFileUtil.closeFile(bufferedOutputStream); afterOperation(); } } public void diffSummarize(String target1, Revision revision1, String target2, Revision revision2, Depth depth, Collection changelists, boolean ignoreAncestry, DiffSummaryCallback receiver) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(target1, target2)); SvnDiffSummarize diffSummarize = svnOperationFactory.createDiffSummarize(); diffSummarize.setSources(getTarget(target1, revision1), getTarget(target2, revision2)); diffSummarize.setDepth(getSVNDepth(depth)); diffSummarize.setApplicalbeChangelists(changelists); diffSummarize.setIgnoreAncestry(ignoreAncestry); diffSummarize.setReceiver(getDiffStatusReceiver(receiver)); diffSummarize.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void diffSummarize(String target, Revision pegRevision, Revision startRevision, Revision endRevision, Depth depth, Collection changelists, boolean ignoreAncestry, DiffSummaryCallback receiver) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(target)); SvnDiffSummarize diffSummarize = svnOperationFactory.createDiffSummarize(); diffSummarize.setSource(getTarget(target, pegRevision), getSVNRevision(startRevision), getSVNRevision(endRevision)); diffSummarize.setDepth(getSVNDepth(depth)); diffSummarize.setApplicalbeChangelists(changelists); diffSummarize.setIgnoreAncestry(ignoreAncestry); diffSummarize.setReceiver(getDiffStatusReceiver(receiver)); diffSummarize.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void properties(String path, Revision revision, Revision pegRevision, Depth depth, Collection changelists, ProplistCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnGetProperties getProperties = svnOperationFactory.createGetProperties(); getProperties.setRevision(getSVNRevision(revision)); getProperties.setDepth(getSVNDepth(depth)); getProperties.setApplicalbeChangelists(changelists); getProperties.setReceiver(getSVNPropertiesReceiver(callback)); getProperties.addTarget(getTarget(path, pegRevision)); getProperties.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void propertySetLocal(Set paths, String name, byte[] value, Depth depth, Collection changelists, boolean force) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(paths)); SvnSetProperty setProperty = svnOperationFactory.createSetProperty(); setProperty.setPropertyName(name); setProperty.setPropertyValue(SVNPropertyValue.create(name, value)); setProperty.setDepth(getSVNDepth(depth)); setProperty.setApplicalbeChangelists(changelists); setProperty.setForce(force); for (String path : paths) { setProperty.addTarget(getTarget(path)); } setProperty.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void propertySetRemote(String path, long baseRev, String name, byte[] value, CommitMessageCallback handler, boolean force, Map revpropTable, CommitCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnRemoteSetProperty remoteSetProperty = svnOperationFactory.createRemoteSetProperty(); remoteSetProperty.setSingleTarget(getTarget(path)); remoteSetProperty.setRevision(SVNRevision.create(baseRev)); remoteSetProperty.setPropertyName(name); remoteSetProperty.setPropertyValue(SVNPropertyValue.create(name, value)); remoteSetProperty.setCommitHandler(getCommitHandler(handler)); remoteSetProperty.setForce(force); remoteSetProperty.setRevisionProperties(getSVNProperties(revpropTable)); remoteSetProperty.setReceiver(getCommitInfoReceiver(callback)); remoteSetProperty.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public byte[] revProperty(String path, String name, Revision rev) throws ClientException { return getProperty(path, name, rev, null, true); } public Map revProperties(String path, Revision rev) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnGetProperties getProperties = svnOperationFactory.createGetProperties(); getProperties.setSingleTarget(getTarget(path)); getProperties.setRevision(getSVNRevision(rev)); getProperties.setRevisionProperties(true); final SVNProperties[] svnProperties = new SVNProperties[1]; getProperties.setReceiver(new ISvnObjectReceiver() { public void receive(SvnTarget target, SVNProperties properties) throws SVNException { svnProperties[0] = properties; } }); getProperties.run(); return getProperties(svnProperties[0]); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void setRevProperty(String path, String name, Revision rev, String value, String originalValue, boolean force) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnSetProperty remoteSetProperty = svnOperationFactory.createSetProperty(); remoteSetProperty.setSingleTarget(getTarget(path)); remoteSetProperty.setPropertyName(name); remoteSetProperty.setRevision(getSVNRevision(rev)); remoteSetProperty.setPropertyValue(SVNPropertyValue.create(value)); remoteSetProperty.setRevisionProperty(true); remoteSetProperty.setForce(force); remoteSetProperty.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public byte[] propertyGet(String path, String name, Revision revision, Revision pegRevision) throws ClientException { return getProperty(path, name, revision, pegRevision, false); } public byte[] fileContent(String path, Revision revision, Revision pegRevision) throws ClientException { beforeOperation(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); streamFileContent(path, revision, pegRevision, byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); } public void streamFileContent(String path, Revision revision, Revision pegRevision, OutputStream stream) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnCat cat = svnOperationFactory.createCat(); cat.setSingleTarget(getTarget(path, pegRevision)); cat.setRevision(getSVNRevision(revision)); cat.setExpandKeywords(false); cat.setOutput(stream); cat.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void relocate(String from, String to, String path, boolean ignoreExternals) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnRelocate relocate = svnOperationFactory.createRelocate(); relocate.setFromUrl(SVNURL.parseURIEncoded(from)); relocate.setToUrl(SVNURL.parseURIEncoded(to)); relocate.setSingleTarget(getTarget(path)); relocate.setIgnoreExternals(ignoreExternals); relocate.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, final BlameCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); final SvnAnnotate annotate = svnOperationFactory.createAnnotate(); annotate.setSingleTarget(getTarget(path, pegRevision)); annotate.setStartRevision(getSVNRevision(revisionStart)); annotate.setEndRevision(getSVNRevision(revisionEnd)); annotate.setIgnoreMimeType(ignoreMimeType); annotate.setUseMergeHistory(includeMergedRevisions); annotate.setReceiver(getAnnotateItemReceiver(callback)); annotate.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public static ClientException getClientException(Throwable e) throws ClientException { ClientException ce = ClientException.fromException(e); ce.initCause(e); if (e instanceof SVNException) { int errorCode = ((SVNException) e).getErrorMessage().getErrorCode().getCode(); try { Field f = ce.getClass().getSuperclass().getDeclaredField(APR_ERROR_FIELD_NAME); if (f != null) { f.setAccessible(true); f.set(ce, errorCode); } } catch (SecurityException e1) { } catch (NoSuchFieldException e1) { } catch (IllegalArgumentException e1) { } catch (IllegalAccessException e1) { } } return ce; } public void setConfigDirectory(String configDir) throws ClientException { this.configDir = configDir; updateSvnOperationsFactory(); } public String getConfigDirectory() throws ClientException { return configDir; } public void cancelOperation() throws ClientException { getEventHandler().cancelOperation(); } public void addToChangelist(Set paths, String changelist, Depth depth, Collection changelists) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(paths)); SvnSetChangelist setChangeList = svnOperationFactory.createSetChangelist(); setChangeList.setChangelistName(changelist); setChangeList.setDepth(getSVNDepth(depth)); setChangeList.setApplicalbeChangelists(changelists); setChangeList.setRemove(false); for (String path : paths) { setChangeList.addTarget(getTarget(path)); } setChangeList.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void removeFromChangelists(Set paths, Depth depth, Collection changelists) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(paths)); SvnSetChangelist setChangelist = svnOperationFactory.createSetChangelist(); setChangelist.setDepth(getSVNDepth(depth)); setChangelist.setApplicalbeChangelists(changelists); setChangelist.setRemove(true); for (String path : paths) { setChangelist.addTarget(getTarget(path)); } setChangelist.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void getChangelists(String rootPath, Collection changelists, Depth depth, final ChangelistCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(rootPath)); SvnGetInfo getInfo = svnOperationFactory.createGetInfo(); getInfo.setSingleTarget(getTarget(rootPath)); getInfo.setApplicalbeChangelists(changelists); getInfo.setDepth(getSVNDepth(depth)); if (callback != null) { getInfo.setReceiver(new ISvnObjectReceiver() { public void receive(SvnTarget target, SvnInfo svnInfo) throws SVNException { SvnWorkingCopyInfo wcInfo = svnInfo.getWcInfo(); if (wcInfo != null) { String path = getFilePath(wcInfo.getPath()); String changelist = wcInfo.getChangelist(); callback.doChangelist(path, changelist); } } }); } getInfo.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void lock(Set path, String comment, boolean force) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnSetLock lock = svnOperationFactory.createSetLock(); lock.setLockMessage(comment); lock.setStealLock(force); for (String targetPath : path) { lock.addTarget(getTarget(targetPath)); } lock.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void unlock(Set path, boolean force) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnUnlock unlock = svnOperationFactory.createUnlock(); unlock.setBreakLock(force); for (String targetPath : path) { unlock.addTarget(getTarget(targetPath)); } unlock.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void info2(String pathOrUrl, Revision revision, Revision pegRevision, Depth depth, Collection changelists, InfoCallback callback) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(pathOrUrl)); SvnGetInfo info = svnOperationFactory.createGetInfo(); info.setSingleTarget(getTarget(pathOrUrl, pegRevision)); info.setRevision(getSVNRevision(revision)); info.setDepth(getSVNDepth(depth)); info.setApplicalbeChangelists(changelists); info.setReceiver(getInfoReceiver(callback)); info.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public String getVersionInfo(String path, String trailUrl, boolean lastChanged) throws ClientException { beforeOperation(); try{ getEventHandler().setPathPrefix(getPathPrefix(path)); final SvnGetStatusSummary getWCId = svnOperationFactory.createGetStatusSummary(); getWCId.setSingleTarget(getTarget(path)); getWCId.setCommitted(lastChanged); getWCId.setTrailUrl(trailUrl); SvnStatusSummary summary = getWCId.run(); if (summary != null) { return summary.toString(); } } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } return null; } public void upgrade(String path) throws ClientException { beforeOperation(); try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnUpgrade upgrade = svnOperationFactory.createUpgrade(); upgrade.setSingleTarget(getTarget(path)); upgrade.run(); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } public void patch(String patchPath, String targetPath, boolean dryRun, int stripCount, boolean reverse, boolean ignoreWhitespace, boolean removeTempfiles, PatchCallback callback) throws ClientException { // TODO throw SVNClientImpl.getClientException(new SVNException(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Patch operation is not implemented yet."))); } private SVNDepth getSVNDepth(Depth depth) { switch (depth) { case empty: return SVNDepth.EMPTY; case exclude: return SVNDepth.EXCLUDE; case files: return SVNDepth.FILES; case immediates: return SVNDepth.IMMEDIATES; case infinity: return SVNDepth.INFINITY; default: return SVNDepth.UNKNOWN; } } private Depth getDepth(SVNDepth depth) { if (depth == SVNDepth.EMPTY) { return Depth.empty; } else if (depth == SVNDepth.EXCLUDE) { return Depth.exclude; } else if (depth == SVNDepth.FILES) { return Depth.files; } else if (depth == SVNDepth.IMMEDIATES) { return Depth.immediates; } else if (depth == SVNDepth.INFINITY) { return Depth.infinity; } else { return Depth.unknown; } } private static SVNStatusType combineStatus(SvnStatus status) { if (status.getNodeStatus() == SVNStatusType.STATUS_CONFLICTED) { if (!status.isVersioned() && status.isConflicted()) { return SVNStatusType.STATUS_MISSING; } return status.getTextStatus(); } else if (status.getNodeStatus() == SVNStatusType.STATUS_MODIFIED) { return status.getTextStatus(); } return status.getNodeStatus(); } private Status getStatus(SvnStatus status) throws SVNException { String repositoryRelativePath = status.getRepositoryRelativePath() == null ? "" : status.getRepositoryRelativePath(); SVNURL repositoryRootUrl = status.getRepositoryRootUrl(); String itemUrl = repositoryRootUrl == null ? null : getUrlString(repositoryRootUrl.appendPath(repositoryRelativePath, false)); return new Status( getFilePath(status.getPath()), itemUrl, getNodeKind(status.getKind()), status.getRevision(), status.getChangedRevision(), getLongDate(status.getChangedDate()), status.getChangedAuthor(), getStatusKind(combineStatus(status)), getStatusKind(status.getPropertiesStatus()), getStatusKind(status.getRepositoryTextStatus()), getStatusKind(status.getRepositoryPropertiesStatus()), status.isWcLocked(), status.isCopied(), status.isConflicted(), status.isSwitched(), status.isFileExternal(), getLock(status.getLock()), getLock(status.getRepositoryLock()), status.getRepositoryChangedRevision(), getLongDate(status.getRepositoryChangedDate()), getNodeKind(status.getRepositoryKind()), status.getRepositoryChangedAuthor(), status.getChangelist() ); } static Lock getLock(SVNLock lock) { if (lock == null) { return null; } return new Lock(lock.getOwner(), lock.getPath(), lock.getID(), lock.getComment(), getLongDate(lock.getCreationDate()), getLongDate(lock.getExpirationDate())); } private static long getLongDate(Date date) { SVNDate svnDate = SVNDate.fromDate(date); return svnDate.getTimeInMicros(); } private SvnTarget getTarget(String path, Revision revision) { SVNRevision svnRevision = getSVNRevision(revision); if (SVNPathUtil.isURL(path)) { try { return SvnTarget.fromURL(SVNURL.parseURIEncoded(path), svnRevision); } catch (SVNException e) { //never happens if SVNPathUtil#isURL works correctly throw new IllegalArgumentException(e); } } return SvnTarget.fromFile(new File(path), svnRevision); } private SvnTarget getTarget(String path) { return getTarget(path, null); } @SuppressWarnings("deprecation") private Status.Kind getStatusKind(SVNStatusType statusType) { if (statusType == SVNStatusType.STATUS_ADDED) { return Status.Kind.added; } else if (statusType == SVNStatusType.STATUS_CONFLICTED) { return Status.Kind.conflicted; } else if (statusType == SVNStatusType.STATUS_DELETED) { return Status.Kind.deleted; } else if (statusType == SVNStatusType.STATUS_EXTERNAL) { return Status.Kind.external; } else if (statusType == SVNStatusType.STATUS_IGNORED) { return Status.Kind.ignored; } else if (statusType == SVNStatusType.STATUS_INCOMPLETE) { return Status.Kind.incomplete; } else if (statusType == SVNStatusType.STATUS_MERGED) { return Status.Kind.merged; } else if (statusType == SVNStatusType.STATUS_MISSING) { return Status.Kind.missing; } else if (statusType == SVNStatusType.STATUS_MODIFIED) { return Status.Kind.modified; } else if (statusType == SVNStatusType.STATUS_NAME_CONFLICT) { return Status.Kind.unversioned; } else if (statusType == SVNStatusType.STATUS_NONE) { return Status.Kind.none; } else if (statusType == SVNStatusType.STATUS_NORMAL) { return Status.Kind.normal; } else if (statusType == SVNStatusType.STATUS_OBSTRUCTED) { return Status.Kind.obstructed; } else if (statusType == SVNStatusType.STATUS_REPLACED) { return Status.Kind.replaced; } else if (statusType == SVNStatusType.STATUS_UNVERSIONED) { return Status.Kind.unversioned; } else { throw new IllegalArgumentException("Unknown status type: " + statusType); } } private static NodeKind getNodeKind(SVNNodeKind kind) { if (kind == SVNNodeKind.DIR) { return NodeKind.dir; } else if (kind == SVNNodeKind.FILE) { return NodeKind.file; } else if (kind == SVNNodeKind.NONE) { return NodeKind.none; } else { return NodeKind.unknown; } } static SVNRevision getSVNRevision(Revision revision) { if (revision == null) { return SVNRevision.UNDEFINED; } switch (revision.getKind()) { case base: return SVNRevision.BASE; case committed: return SVNRevision.COMMITTED; case date: Revision.DateSpec dateSpec = (Revision.DateSpec) revision; return SVNRevision.create(dateSpec.getDate()); case head: return SVNRevision.HEAD; case number: Revision.Number number = (Revision.Number) revision; return SVNRevision.create(number.getNumber()); case previous: return SVNRevision.PREVIOUS; case working: return SVNRevision.WORKING; case unspecified: default: return SVNRevision.UNDEFINED; } } private SVNProperties getSVNProperties(Map revpropTable) { return SVNProperties.wrap(revpropTable); } private CommitItem getSvnCommitItem(SvnCommitItem commitable) { if (commitable == null) { return null; } return new CommitItem(getFilePath(commitable.getPath()), getNodeKind(commitable.getKind()), commitable.getFlags(), getUrlString(commitable.getUrl()), getUrlString(commitable.getCopyFromUrl()), commitable.getCopyFromRevision()); } private String getFilePath(File path) { if (path == null) { return null; } return path.getPath().replace(File.separatorChar, '/'); } private String getUrlString(SVNURL url) { if (url == null) { return null; } return url.toString(); } private ISvnObjectReceiver getStatusReceiver(final StatusCallback callback) { if (callback == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SvnStatus status) throws SVNException { callback.doStatus(getFilePath(target.getFile()), getStatus(status)); } }; } private ISvnCommitHandler getCommitHandler(final CommitMessageCallback callback) { if (callback == null) { return null; } return new ISvnCommitHandler() { public String getCommitMessage(String message, SvnCommitItem[] commitables) throws SVNException { Set commitItems = new HashSet(); for (SvnCommitItem commitable : commitables) { commitItems.add(getSvnCommitItem(commitable)); } return callback.getLogMessage(commitItems); } public SVNProperties getRevisionProperties(String message, SvnCommitItem[] commitables, SVNProperties revisionProperties) throws SVNException { return revisionProperties; } }; } private Collection getSvnRevisionRanges(List ranges) { if (ranges == null) { return null; } Collection svnRevisionRanges = new ArrayList(ranges.size()); for (RevisionRange range : ranges) { svnRevisionRanges.add(getSvnRevisionRange(range)); } return svnRevisionRanges; } private SvnRevisionRange getSvnRevisionRange(RevisionRange range) { return SvnRevisionRange.create(getSVNRevision(range.getFromRevision()), getSVNRevision(range.getToRevision())); } private String[] getRevisionPropertiesNames(Set revProps) { if (revProps == null) { return null; } String[] revisionPropertiesNames = new String[revProps.size()]; int i = 0; for (String revProp : revProps) { revisionPropertiesNames[i] = revProp; i++; } return revisionPropertiesNames; } private ISvnObjectReceiver getLogEntryReceiver(final LogMessageCallback callback) { if (callback == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SVNLogEntry svnLogEntry) throws SVNException { callback.singleMessage(getChangePaths(svnLogEntry.getChangedPaths()), svnLogEntry.getRevision(), getProperties(svnLogEntry.getRevisionProperties()), svnLogEntry.hasChildren()); } }; } private Set getChangePaths(Map changedPaths) { if (changedPaths == null) { return null; } Set changePaths = new HashSet(); for (Map.Entry entry : changedPaths.entrySet()) { SVNLogEntryPath svnLogEntryPath = entry.getValue(); //TODO: replace Tristate.Unknown with correct values in the following changePaths.add(new ChangePath(svnLogEntryPath.getPath(), svnLogEntryPath.getCopyRevision(), svnLogEntryPath.getCopyPath(), getChangePathAction(svnLogEntryPath.getType()), getNodeKind(svnLogEntryPath.getKind()), Tristate.Unknown, Tristate.Unknown)); } return changePaths; } private ChangePath.Action getChangePathAction(char type) { if (type == 'A') { return ChangePath.Action.add; } else if (type == 'M') { return ChangePath.Action.modify; } else if (type == 'D') { return ChangePath.Action.delete; } else if (type == 'R') { return ChangePath.Action.replace; } else { throw new IllegalArgumentException("Unknown change action type " + type); } } private Map getProperties(SVNProperties svnProperties) { if (svnProperties == null) { return new HashMap(); } HashMap properties = new HashMap(); Set svnPropertiesNames = svnProperties.nameSet(); for (String svnPropertyName : svnPropertiesNames) { SVNPropertyValue svnPropertyValue = svnProperties.getSVNPropertyValue(svnPropertyName); properties.put(svnPropertyName, SVNPropertyValue.getPropertyAsBytes(svnPropertyValue)); } return properties; } private static Map getRevisionProperties(SVNProperties revisionProperties) { if (revisionProperties == null) { return null; } HashMap properties = new HashMap(); Set svnPropertiesNames = revisionProperties.nameSet(); for (String svnPropertyName : svnPropertiesNames) { SVNPropertyValue svnPropertyValue = revisionProperties.getSVNPropertyValue(svnPropertyName); properties.put(svnPropertyName, SVNPropertyValue.getPropertyAsString(svnPropertyValue)); } return properties; } private ISvnObjectReceiver getSVNPropertiesReceiver(final ProplistCallback callback) { if (callback == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SVNProperties svnProperties) throws SVNException { callback.singlePath(getFilePath(target.getFile()), getProperties(svnProperties)); } }; } private SVNConflictChoice getSVNConflictChoice(Choice choice) { switch (choice) { case chooseBase: return SVNConflictChoice.BASE; case chooseMerged: return SVNConflictChoice.MERGED; case chooseMineConflict: return SVNConflictChoice.MINE_CONFLICT; case chooseMineFull: return SVNConflictChoice.MINE_FULL; case chooseTheirsConflict: return SVNConflictChoice.THEIRS_CONFLICT; case chooseTheirsFull: return SVNConflictChoice.THEIRS_FULL; case postpone: return SVNConflictChoice.POSTPONE; default: throw new IllegalArgumentException("Unknown choice kind: " + choice); } } private byte[] getProperty(String path, final String name, Revision rev, Revision pegRevision, boolean revisionProperties) throws ClientException { try { getEventHandler().setPathPrefix(getPathPrefix(path)); SvnGetProperties getProperties = svnOperationFactory.createGetProperties(); getProperties.setSingleTarget(getTarget(path, pegRevision)); getProperties.setRevision(getSVNRevision(rev)); getProperties.setRevisionProperties(revisionProperties); final SVNPropertyValue[] propertyValue = new SVNPropertyValue[1]; getProperties.setReceiver(new ISvnObjectReceiver() { public void receive(SvnTarget target, SVNProperties svnProperties) throws SVNException { propertyValue[0] = svnProperties.getSVNPropertyValue(name); } }); getProperties.run(); return SVNPropertyValue.getPropertyAsBytes(propertyValue[0]); } catch (SVNException e) { throw getClientException(e); } finally { afterOperation(); } } private DiffSummary getDiffSummary(SvnDiffStatus diffStatus) { return new DiffSummary(diffStatus.getPath(), getDiffKind(diffStatus.getModificationType()), diffStatus.isPropertiesModified(), getNodeKind(diffStatus.getKind())); } private DiffSummary.DiffKind getDiffKind(SVNStatusType type) { if (type == SVNStatusType.STATUS_ADDED) { return DiffSummary.DiffKind.added; } else if (type == SVNStatusType.STATUS_DELETED) { return DiffSummary.DiffKind.deleted; } else if (type == SVNStatusType.STATUS_MODIFIED) { return DiffSummary.DiffKind.modified; } else if (type == SVNStatusType.STATUS_NORMAL) { return DiffSummary.DiffKind.normal; } else { throw new IllegalArgumentException("Unknown status type: " + type); } } private ISvnObjectReceiver getDiffStatusReceiver(final DiffSummaryCallback receiver) { if (receiver == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SvnDiffStatus diffStatus) throws SVNException { if (diffStatus != null && diffStatus.getModificationType() == SVNStatusType.STATUS_NONE) { return; } receiver.onSummary(getDiffSummary(diffStatus)); } }; } private ISvnObjectReceiver getCommitInfoReceiver(final CommitCallback callback) { if (callback == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SVNCommitInfo commitInfo) throws SVNException { try { SVNURL repositoryRoot = target.getURL(); callback.commitInfo(getCommitInfo(commitInfo, repositoryRoot)); } catch (ParseException e) { throwSvnException(e); } } }; } private void fillLocalAndRemoteTargets(Set path, Set localPaths, Set remoteUrls) { for (String targetPath : path) { if (SVNPathUtil.isURL(targetPath)) { remoteUrls.add(targetPath); } else { localPaths.add(targetPath); } } } private CommitInfo getCommitInfo(SVNCommitInfo commitInfo, SVNURL repositoryRoot) throws ParseException { return new CommitInfo(commitInfo.getNewRevision(), SVNDate.formatDate(commitInfo.getDate()), commitInfo.getAuthor(), getErrorMessageString(commitInfo.getErrorMessage()), getUrlString(repositoryRoot)); } private static String getErrorMessageString(SVNErrorMessage errorMessage) { if (errorMessage == null) { return null; } return errorMessage.getMessage(); } private SvnCopySource getSvnCopySource(CopySource localSource) { return SvnCopySource.create(getTarget(localSource.getPath(), localSource.getPegRevision()), getSVNRevision(localSource.getRevision())); } private void mkdirLocal(Set localPaths, boolean makeParents) throws ClientException { if (localPaths == null || localPaths.size() == 0) { return; } SvnScheduleForAddition add = svnOperationFactory.createScheduleForAddition(); add.setAddParents(makeParents); add.setMkDir(true); for (String localPath : localPaths) { add.addTarget(getTarget(localPath)); } try { add.run(); } catch (SVNException e) { throw getClientException(e); } } private void mkdirRemote(Set remoteUrls, boolean makeParents, Map revpropTable, CommitMessageCallback handler, final CommitCallback callback) throws ClientException { if (remoteUrls == null || remoteUrls.size() == 0) { return; } SvnRemoteMkDir mkdir = svnOperationFactory.createMkDir(); mkdir.setMakeParents(makeParents); mkdir.setRevisionProperties(getSVNProperties(revpropTable)); mkdir.setCommitHandler(getCommitHandler(handler)); mkdir.setReceiver(getCommitInfoReceiver(callback)); for (String remoteUrl : remoteUrls) { mkdir.addTarget(getTarget(remoteUrl)); } try { mkdir.run(); } catch (SVNException e) { throw getClientException(e); } } private void removeLocal(Set localPaths, boolean force, boolean keepLocal) throws ClientException { if (localPaths == null || localPaths.size() == 0) { return; } SvnScheduleForRemoval remove = svnOperationFactory.createScheduleForRemoval(); remove.setForce(force); remove.setDeleteFiles(!keepLocal); for (String localPath : localPaths) { remove.addTarget(getTarget(localPath)); } try { remove.run(); } catch (SVNException e) { throw getClientException(e); } } private void removeRemote(Set remoteUrls, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { if (remoteUrls == null || remoteUrls.size() == 0) { return; } SvnRemoteDelete remoteDelete = svnOperationFactory.createRemoteDelete(); remoteDelete.setRevisionProperties(getSVNProperties(revpropTable)); remoteDelete.setCommitHandler(getCommitHandler(handler)); remoteDelete.setReceiver(getCommitInfoReceiver(callback)); for (String remoteUrl : remoteUrls) { remoteDelete.addTarget(getTarget(remoteUrl)); } try { remoteDelete.run(); } catch (SVNException e) { throw getClientException(e); } } private void moveLocal(Set srcPaths, String destPath, boolean force, boolean moveAsChild, boolean makeParents) throws ClientException { if (srcPaths == null || srcPaths.size() == 0) { return; } SvnCopy copy = svnOperationFactory.createCopy(); copy.setSingleTarget(getTarget(destPath)); copy.setMakeParents(makeParents); copy.setFailWhenDstExists(!moveAsChild); copy.setMove(true); for (String localPath : srcPaths) { copy.addCopySource(SvnCopySource.create(getTarget(localPath), SVNRevision.UNDEFINED)); } try { copy.run(); } catch (SVNException e) { throw getClientException(e); } } private void moveRemote(Set srcPaths, String destPath, boolean moveAsChild, boolean makeParents, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { if (srcPaths == null || srcPaths.size() == 0) { return; } SvnRemoteCopy remoteCopy = svnOperationFactory.createRemoteCopy(); remoteCopy.setSingleTarget(getTarget(destPath)); remoteCopy.setMakeParents(makeParents); remoteCopy.setRevisionProperties(getSVNProperties(revpropTable)); remoteCopy.setCommitHandler(getCommitHandler(handler)); remoteCopy.setReceiver(getCommitInfoReceiver(callback)); remoteCopy.setFailWhenDstExists(!moveAsChild); remoteCopy.setMove(true); for (String remoteUrl : srcPaths) { remoteCopy.addCopySource(SvnCopySource.create(getTarget(remoteUrl), SVNRevision.UNDEFINED)); } try { remoteCopy.run(); } catch (SVNException e) { throw getClientException(e); } } private void copyLocal(List localSources, String destPath, boolean copyAsChild, boolean makeParents, boolean ignoreExternals) throws ClientException { if (localSources == null || localSources.size() == 0) { return; } SvnCopy copy = svnOperationFactory.createCopy(); copy.setSingleTarget(getTarget(destPath)); copy.setMakeParents(makeParents); copy.setIgnoreExternals(ignoreExternals); copy.setFailWhenDstExists(!copyAsChild); copy.setMove(false); for (CopySource localSource : localSources) { copy.addCopySource(getSvnCopySource(localSource)); } try { copy.run(); } catch (SVNException e) { throw getClientException(e); } } private void copyRemote(List remoteSources, String destPath, boolean copyAsChild, boolean makeParents, Map revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException { if (remoteSources == null || remoteSources.size() == 0) { return; } SvnRemoteCopy remoteCopy = svnOperationFactory.createRemoteCopy(); remoteCopy.setSingleTarget(getTarget(destPath)); remoteCopy.setMakeParents(makeParents); remoteCopy.setRevisionProperties(getSVNProperties(revpropTable)); remoteCopy.setCommitHandler(getCommitHandler(handler)); remoteCopy.setReceiver(getCommitInfoReceiver(callback)); remoteCopy.setFailWhenDstExists(!copyAsChild); remoteCopy.setMove(false); for (CopySource remoteSource : remoteSources) { remoteCopy.addCopySource(getSvnCopySource(remoteSource)); } try { remoteCopy.run(); } catch (SVNException e) { throw getClientException(e); } } private ISvnObjectReceiver getInfoReceiver(final InfoCallback callback) { if (callback == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SvnInfo info) throws SVNException { try { callback.singleInfo(getInfo(info)); } catch (ClientException e) { throwSvnException(e); } } }; } private Info getInfo(SvnInfo info) throws ClientException { String url = getUrlString(info.getUrl()); String repositoryRoot = getUrlString(info.getRepositoryRootUrl()); boolean hasWcInfo = info.getWcInfo() != null; String path = (repositoryRoot != null && url != null) ? SVNPathUtil.getRelativePath(repositoryRoot, url) : (hasWcInfo ? getFilePath(info.getWcInfo().getPath()) : null); return new Info(path, hasWcInfo ? getFilePath(info.getWcInfo().getWcRoot()) : null, url, info.getRevision(), getNodeKind(info.getKind()), repositoryRoot, info.getRepositoryUuid(), info.getLastChangedRevision(), getLongDate(info.getLastChangedDate()), info.getLastChangedAuthor(), getLock(info.getLock()), hasWcInfo, hasWcInfo ? getScheduleKind(info.getWcInfo().getSchedule()) : null, hasWcInfo ? getUrlString(info.getWcInfo().getCopyFromUrl()) : null, hasWcInfo ? info.getWcInfo().getCopyFromRevision() : -1, hasWcInfo ? info.getWcInfo().getRecordedTime() : 0, hasWcInfo ? getChecksum(info.getWcInfo().getChecksum()) : null, hasWcInfo ? info.getWcInfo().getChangelist() : null, hasWcInfo ? info.getWcInfo().getRecordedSize() : -1, info.getSize(), hasWcInfo ? getDepth(info.getWcInfo().getDepth()) : null, hasWcInfo ? getConflictDescriptors(info.getWcInfo().getConflicts()) : null ); } private Set getConflictDescriptors(Collection conflicts) throws ClientException { HashSet conflictDescriptors = new HashSet(); for (SVNConflictDescription conflict : conflicts) { conflictDescriptors.add(getConflictDescription(conflict)); } return conflictDescriptors; } private Checksum getChecksum(SvnChecksum checksum) { if (checksum == null) { return null; } return new Checksum(checksum.getDigest().getBytes(), getChecksumKind(checksum.getKind())); } private Checksum.Kind getChecksumKind(SvnChecksum.Kind kind) { if (kind == null) { return null; } switch (kind) { case md5: return Checksum.Kind.MD5; case sha1: return Checksum.Kind.SHA1; default: throw new IllegalArgumentException("Unsupported checksum kind: " + kind); } } private Info.ScheduleKind getScheduleKind(SvnSchedule schedule) { if (schedule == SvnSchedule.ADD) { return Info.ScheduleKind.add; } else if (schedule == SvnSchedule.DELETE) { return Info.ScheduleKind.delete; } else if (schedule == SvnSchedule.NORMAL) { return Info.ScheduleKind.normal; } else if (schedule == SvnSchedule.REPLACE) { return Info.ScheduleKind.replace; } else { throw new IllegalArgumentException("Unknown schedule kind: " + schedule); } } private Mergeinfo getMergeinfo(Map mergeInfoMap) { if (mergeInfoMap == null) { return null; } Mergeinfo mergeinfo = new Mergeinfo(); for (Map.Entry entry : mergeInfoMap.entrySet()) { SVNURL url = entry.getKey(); SVNMergeRangeList mergeRangeList = entry.getValue(); if (mergeRangeList == null) { continue; } String urlString = getUrlString(url); SVNMergeRange[] ranges = mergeRangeList.getRanges(); for (SVNMergeRange range : ranges) { if (range == null) { continue; } mergeinfo.addRevisionRange(urlString, getRevisionRange(range)); } } return mergeinfo; } private static RevisionRange getRevisionRange(SVNMergeRange revisionRange) { if (revisionRange == null) { return null; } long startRevision = revisionRange.getStartRevision(); long endRevision = revisionRange.getEndRevision(); return new RevisionRange(Revision.getInstance(startRevision), Revision.getInstance(endRevision)); } private ISvnObjectReceiver getAnnotateItemReceiver(final BlameCallback callback) { if (callback == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SvnAnnotateItem annotateItem) throws SVNException { try { if (annotateItem.isLine()) { Map revisionProperties = getProperties(annotateItem.getRevisionProperties()); Map mergedRevisionProperties = getProperties(annotateItem.getMergedRevisionProperties()); callback.singleLine(annotateItem.getLineNumber(), annotateItem.getRevision(), (revisionProperties == null || revisionProperties.isEmpty()) ? null : revisionProperties, annotateItem.getMergedRevision(), (mergedRevisionProperties == null || mergedRevisionProperties.isEmpty()) ? null : mergedRevisionProperties, annotateItem.getMergedPath(), annotateItem.getLine(), !SVNRevision.isValidRevisionNumber(annotateItem.getRevision())); } } catch (ClientException e) { throwSvnException(e); } } }; } private ISVNConflictHandler getConflictHandler(final ConflictResolverCallback callback) { if (callback == null) { return null; } return new ISVNConflictHandler() { public SVNConflictResult handleConflict(SVNConflictDescription conflictDescription) throws SVNException { try { return getSVNConflictResult(callback.resolve(getConflictDescription(conflictDescription))); } catch (SubversionException e) { throwSvnException(e); return null; } } }; } private ConflictDescriptor getConflictDescription(SVNConflictDescription conflictDescription) throws ClientException { ConflictVersion srcLeft = null; ConflictVersion srcRight = null; ConflictDescriptor.Operation operation = Operation.none; if (conflictDescription instanceof SVNTreeConflictDescription) { SVNTreeConflictDescription treeConflictDescription = (SVNTreeConflictDescription) conflictDescription; srcLeft = getConflictVersion(treeConflictDescription.getSourceLeftVersion()); srcRight = getConflictVersion(treeConflictDescription.getSourceRightVersion()); operation = getConflictDescriptorOperation(treeConflictDescription.getOperation()); } return new ConflictDescriptor( getFilePath(conflictDescription.getPath()), getConflictDescriptorKind(conflictDescription), getNodeKind(conflictDescription.getNodeKind()), conflictDescription.getPropertyName(), conflictDescription.getMergeFiles().isBinary(), conflictDescription.getMergeFiles().getMimeType(), getConflictDescriptorAction(conflictDescription.getConflictAction()), getConflictDescriptorReason(conflictDescription.getConflictReason()), operation, getFilePath(conflictDescription.getMergeFiles().getBaseFile()), getFilePath(conflictDescription.getMergeFiles().getRepositoryFile()), getFilePath(conflictDescription.getMergeFiles().getLocalFile()), getFilePath(conflictDescription.getMergeFiles().getResultFile()), srcLeft, srcRight ); } private ConflictDescriptor.Operation getConflictDescriptorOperation(SVNOperation operation) { if (operation == null) { return null; } if (operation == SVNOperation.MERGE) { return ConflictDescriptor.Operation.merge; } else if (operation == SVNOperation.UPDATE) { return ConflictDescriptor.Operation.update; } else if (operation == SVNOperation.SWITCH) { return ConflictDescriptor.Operation.switched; } else if (operation == SVNOperation.NONE) { return ConflictDescriptor.Operation.none; } else { throw new IllegalArgumentException("Unknown operation: " + operation); } } private ConflictVersion getConflictVersion(SVNConflictVersion conflictVersion) { if (conflictVersion == null) { return null; } return new ConflictVersion(getUrlString(conflictVersion.getRepositoryRoot()), conflictVersion.getPegRevision(), conflictVersion.getPath(), getNodeKind(conflictVersion.getKind())); } private SVNConflictResult getSVNConflictResult(ConflictResult conflictResult) { return new SVNConflictResult(getSVNConflictChoice(conflictResult.getChoice()), getFile(conflictResult.getMergedPath())); } private ConflictDescriptor.Action getConflictDescriptorAction(SVNConflictAction conflictAction) { if (conflictAction == null) { return null; } if (conflictAction == SVNConflictAction.ADD) { return ConflictDescriptor.Action.add; } else if (conflictAction == SVNConflictAction.DELETE) { return ConflictDescriptor.Action.delete; } else if (conflictAction == SVNConflictAction.EDIT) { return ConflictDescriptor.Action.edit; } else if (conflictAction == SVNConflictAction.REPLACE) { //TODO: change to REPLACE when available in JavaHL API return ConflictDescriptor.Action.add; } else { throw new IllegalArgumentException("Unknown conflict action: " + conflictAction); } } private ConflictDescriptor.Reason getConflictDescriptorReason(SVNConflictReason conflictReason) { if (conflictReason == null) { return null; } if (conflictReason == SVNConflictReason.ADDED) { return ConflictDescriptor.Reason.added; } else if (conflictReason == SVNConflictReason.DELETED) { return ConflictDescriptor.Reason.deleted; } else if (conflictReason == SVNConflictReason.EDITED) { return ConflictDescriptor.Reason.edited; } else if (conflictReason == SVNConflictReason.MISSING) { return ConflictDescriptor.Reason.missing; } else if (conflictReason == SVNConflictReason.OBSTRUCTED) { return ConflictDescriptor.Reason.obstructed; } else if (conflictReason == SVNConflictReason.REPLACED) { //TODO: change to REPLACE when available in JavaHL API return ConflictDescriptor.Reason.added; } else if (conflictReason == SVNConflictReason.UNVERSIONED) { return ConflictDescriptor.Reason.unversioned; } else { throw new IllegalArgumentException("Unknown conflict reason: " + conflictReason); } } private static ClientNotifyInformation.Action getClientNotifyInformationAction(SVNEventAction action) { if (action == null) { return null; } if (action == SVNEventAction.ADD) { return ClientNotifyInformation.Action.add; } else if (action == SVNEventAction.ANNOTATE) { return ClientNotifyInformation.Action.blame_revision; } else if (action == SVNEventAction.CHANGELIST_CLEAR) { return ClientNotifyInformation.Action.changelist_clear; } else if (action == SVNEventAction.CHANGELIST_MOVED) { return ClientNotifyInformation.Action.changelist_moved; } else if (action == SVNEventAction.CHANGELIST_SET) { return ClientNotifyInformation.Action.changelist_set; } else if (action == SVNEventAction.COMMIT_ADDED) { return ClientNotifyInformation.Action.commit_added; } else if (action == SVNEventAction.COMMIT_COMPLETED) { return null; } else if (action == SVNEventAction.COMMIT_DELETED) { return ClientNotifyInformation.Action.commit_deleted; } else if (action == SVNEventAction.COMMIT_DELTA_SENT) { return ClientNotifyInformation.Action.commit_postfix_txdelta; } else if (action == SVNEventAction.COMMIT_REPLACED) { return ClientNotifyInformation.Action.commit_replaced; } else if (action == SVNEventAction.COMMIT_MODIFIED) { return ClientNotifyInformation.Action.commit_modified; } else if (action == SVNEventAction.COPY) { return ClientNotifyInformation.Action.copy; } else if (action == SVNEventAction.DELETE) { return ClientNotifyInformation.Action.delete; } else if (action == SVNEventAction.FAILED_EXTERNAL) { return ClientNotifyInformation.Action.failed_external; } else if (action == SVNEventAction.FAILED_REVERT) { return ClientNotifyInformation.Action.failed_revert; } else if (action == SVNEventAction.FOREIGN_MERGE_BEGIN) { return ClientNotifyInformation.Action.foreign_merge_begin; } else if (action == SVNEventAction.LOCK_FAILED) { return ClientNotifyInformation.Action.failed_lock; } else if (action == SVNEventAction.LOCKED) { return ClientNotifyInformation.Action.locked; } else if (action == SVNEventAction.MERGE_BEGIN) { return ClientNotifyInformation.Action.merge_begin; } else if (action == SVNEventAction.MERGE_COMPLETE) { return ClientNotifyInformation.Action.merge_completed; } else if (action == SVNEventAction.PATCH) { return ClientNotifyInformation.Action.patch; } else if (action == SVNEventAction.PATCH_APPLIED_HUNK) { return ClientNotifyInformation.Action.patch_applied_hunk; } else if (action == SVNEventAction.PATCH_REJECTED_HUNK) { return ClientNotifyInformation.Action.patch_rejected_hunk; } else if (action == SVNEventAction.PROGRESS) { return null; } else if (action == SVNEventAction.PROPERTY_ADD) { return ClientNotifyInformation.Action.property_added; } else if (action == SVNEventAction.PROPERTY_DELETE) { return ClientNotifyInformation.Action.property_deleted; } else if (action == SVNEventAction.PROPERTY_DELETE_NONEXISTENT) { return ClientNotifyInformation.Action.property_deleted_nonexistent; } else if (action == SVNEventAction.PROPERTY_MODIFY) { return ClientNotifyInformation.Action.property_modified; } else if (action == SVNEventAction.RESOLVED) { return ClientNotifyInformation.Action.resolved; } else if (action == SVNEventAction.RESTORE) { return ClientNotifyInformation.Action.restore; } else if (action == SVNEventAction.REVERT) { return ClientNotifyInformation.Action.revert; } else if (action == SVNEventAction.REVPROP_DELETE) { return ClientNotifyInformation.Action.revprop_deleted; } else if (action == SVNEventAction.REVPROPER_SET) { return ClientNotifyInformation.Action.revprop_set; } else if (action == SVNEventAction.SKIP) { return ClientNotifyInformation.Action.skip; } else if (action == SVNEventAction.SKIP_CONFLICTED) { return ClientNotifyInformation.Action.skip_conflicted; } else if (action == SVNEventAction.STATUS_COMPLETED) { return ClientNotifyInformation.Action.status_completed; } else if (action == SVNEventAction.STATUS_EXTERNAL) { return ClientNotifyInformation.Action.status_external; } else if (action == SVNEventAction.TREE_CONFLICT) { return ClientNotifyInformation.Action.tree_conflict; } else if (action == SVNEventAction.UNLOCK_FAILED) { return ClientNotifyInformation.Action.failed_unlock; } else if (action == SVNEventAction.UNLOCKED) { return ClientNotifyInformation.Action.unlocked; } else if (action == SVNEventAction.UPDATE_ADD) { return ClientNotifyInformation.Action.update_add; } else if (action == SVNEventAction.UPDATE_COMPLETED) { return ClientNotifyInformation.Action.update_completed; } else if (action == SVNEventAction.UPDATE_DELETE) { return ClientNotifyInformation.Action.update_delete; } else if (action == SVNEventAction.UPDATE_EXISTS) { return ClientNotifyInformation.Action.exists; } else if (action == SVNEventAction.UPDATE_EXTERNAL) { return ClientNotifyInformation.Action.update_external; } else if (action == SVNEventAction.UPDATE_EXTERNAL_REMOVED) { return ClientNotifyInformation.Action.update_external_removed; } else if (action == SVNEventAction.UPDATE_NONE) { return ClientNotifyInformation.Action.update_update; } else if (action == SVNEventAction.UPDATE_REPLACE) { return ClientNotifyInformation.Action.update_replaced; } else if (action == SVNEventAction.UPDATE_SHADOWED_ADD) { return ClientNotifyInformation.Action.update_shadowed_add; } else if (action == SVNEventAction.UPDATE_SHADOWED_DELETE) { return ClientNotifyInformation.Action.update_shadowed_delete; } else if (action == SVNEventAction.UPDATE_SHADOWED_UPDATE) { return ClientNotifyInformation.Action.update_shadowed_update; } else if (action == SVNEventAction.UPDATE_SKIP_ACCESS_DENINED) { return ClientNotifyInformation.Action.update_skip_access_denied; } else if (action == SVNEventAction.UPDATE_SKIP_OBSTRUCTION) { return ClientNotifyInformation.Action.update_skip_obstruction; } else if (action == SVNEventAction.UPDATE_SKIP_WORKING_ONLY) { return ClientNotifyInformation.Action.update_skip_working_only; } else if (action == SVNEventAction.UPDATE_STARTED) { return ClientNotifyInformation.Action.update_started; } else if (action == SVNEventAction.UPDATE_UPDATE) { return ClientNotifyInformation.Action.update_update; } else if (action == SVNEventAction.UPGRADE) { return ClientNotifyInformation.Action.upgraded_path; } else if (action == SVNEventAction.UPGRADED_PATH) { return ClientNotifyInformation.Action.upgraded_path; } else if (action == SVNEventAction.PATH_NONEXISTENT) { return ClientNotifyInformation.Action.path_nonexistent; } else if (action == SVNEventAction.MERGE_ELIDE_INFO) { return ClientNotifyInformation.Action.merge_elide_info; } else if (action == SVNEventAction.MERGE_RECORD_INFO) { return ClientNotifyInformation.Action.merge_record_info; } else if (action == SVNEventAction.MERGE_RECORD_INFO_BEGIN) { return ClientNotifyInformation.Action.merge_record_info_begin; } else if (action == SVNEventAction.MERGE_RECORD_INFO_BEGIN) { return ClientNotifyInformation.Action.merge_record_info_begin; } return null; } private ConflictDescriptor.Kind getConflictDescriptorKind(SVNConflictDescription conflictDescription) { if (conflictDescription == null) { return null; } if (conflictDescription.isTextConflict()) { return ConflictDescriptor.Kind.text; } else if (conflictDescription.isPropertyConflict()) { return ConflictDescriptor.Kind.property; } else if (conflictDescription.isTreeConflict()) { return ConflictDescriptor.Kind.tree; } else { throw new IllegalArgumentException("Unknown conflict kind: " + conflictDescription); } } private File getFile(String path) { if (path == null) { return null; } return new File(path); } private ISvnObjectReceiver getDirEntryReceiver(final ListCallback callback) { if (callback == null) { return null; } return new ISvnObjectReceiver() { public void receive(SvnTarget target, SVNDirEntry dirEntry) throws SVNException { callback.doEntry(getDirEntry(dirEntry), getLock(dirEntry.getLock())); } }; } private DirEntry getDirEntry(SVNDirEntry dirEntry) { if (dirEntry == null) { return null; } String repositoryRootString = getUrlString(dirEntry.getRepositoryRoot()); String urlString = getUrlString(dirEntry.getURL()); String absolutePath = SVNPathUtil.getRelativePath(repositoryRootString, urlString); return new DirEntry(dirEntry.getRelativePath(), absolutePath, getNodeKind(dirEntry.getKind()), dirEntry.getSize(), dirEntry.hasProperties(), dirEntry.getRevision(), getLongDate(dirEntry.getDate()), dirEntry.getAuthor()); } static ClientNotifyInformation getClientNotifyInformation(String pathPrefix, SVNEvent event, String path) { ClientNotifyInformation.Action action = getClientNotifyInformationAction(event.getAction()); if (action == null) { return null; } long hunkOriginalStart = -1; long hunkOriginalLength = -1; long hunkModifiedStart = -1; long hunkModifiedLength = -1; long hunkMatchedLine = -1; int hunkFuzz = -1; Object info = event.getInfo(); if (info != null && info instanceof SVNPatchHunkInfo) { SVNPatchHunkInfo hunkInfo = (SVNPatchHunkInfo) info; hunkOriginalStart = hunkInfo.getHunk().getOriginal().getStart(); hunkOriginalLength = hunkInfo.getHunk().getOriginal().getLength(); hunkModifiedStart = hunkInfo.getHunk().getModified().getStart(); hunkModifiedLength = hunkInfo.getHunk().getModified().getLength(); hunkFuzz = hunkInfo.getFuzz(); } return new ClientNotifyInformation(path, action, getNodeKind(event.getNodeKind()), event.getMimeType(), getLock(event.getLock()), getErrorMessageString(event.getErrorMessage()), getClientNotifyInformationStatus(event.getContentsStatus()), getClientNotifyInformationStatus(event.getPropertiesStatus()), getClientNotifyInformationLockStatus(event.getLockStatus()), event.getRevision(), event.getChangelistName(), getRevisionRange(event.getMergeRange()), pathPrefix, event.getPropertyName(), getRevisionProperties(event.getRevisionProperties()), event.getPreviousRevision(), hunkOriginalStart, hunkOriginalLength, hunkModifiedStart, hunkModifiedLength, hunkMatchedLine, hunkFuzz ); } private static ClientNotifyInformation.LockStatus getClientNotifyInformationLockStatus(SVNStatusType lockStatus) { if (lockStatus == null) { return null; } if (lockStatus == SVNStatusType.LOCK_LOCKED) { return ClientNotifyInformation.LockStatus.locked; } else if (lockStatus == SVNStatusType.LOCK_INAPPLICABLE || lockStatus == SVNStatusType.INAPPLICABLE) { return ClientNotifyInformation.LockStatus.inapplicable; } else if (lockStatus == SVNStatusType.LOCK_UNCHANGED) { return ClientNotifyInformation.LockStatus.unchanged; } else if (lockStatus == SVNStatusType.LOCK_UNKNOWN) { return ClientNotifyInformation.LockStatus.unknown; } else if (lockStatus == SVNStatusType.LOCK_UNLOCKED) { return ClientNotifyInformation.LockStatus.unlocked; } else { throw new IllegalArgumentException("Unknown lock status: " + lockStatus); } } private static ClientNotifyInformation.Status getClientNotifyInformationStatus(SVNStatusType status) { if (status == null) { return null; } if (status == SVNStatusType.CHANGED) { return ClientNotifyInformation.Status.changed; } else if (status == SVNStatusType.CONFLICTED) { return ClientNotifyInformation.Status.conflicted; } else if (status == SVNStatusType.CONFLICTED_UNRESOLVED) { return ClientNotifyInformation.Status.conflicted; } else if (status == SVNStatusType.INAPPLICABLE) { return ClientNotifyInformation.Status.inapplicable; } else if (status == SVNStatusType.MERGED) { return ClientNotifyInformation.Status.merged; } else if (status == SVNStatusType.MISSING) { return ClientNotifyInformation.Status.missing; } else if (status == SVNStatusType.OBSTRUCTED) { return ClientNotifyInformation.Status.obstructed; } else if (status == SVNStatusType.UNCHANGED) { return ClientNotifyInformation.Status.unchanged; } else if (status == SVNStatusType.UNKNOWN) { return ClientNotifyInformation.Status.unknown; } else { throw new IllegalArgumentException("Unknown status type: " + status); } } private String getPathPrefix(String pathOrUrl) { if (pathOrUrl == null) { return null; } if (SVNPathUtil.isURL(pathOrUrl)) { return null; } File file = getFile(pathOrUrl); if (file == null) { return null; } boolean isFile = file.isFile(); if (isFile) { File parentFile = SVNFileUtil.getParentFile(file); if (parentFile == null) { return null; } return getFilePath(parentFile.getAbsoluteFile()); } return getFilePath(file.getAbsoluteFile()); } private String getPathPrefix(Collection pathsOrUrls) { if (pathsOrUrls == null || pathsOrUrls.size() == 0) { return null; } String commonAncestor = null; for (Object pathOrUrl : pathsOrUrls) { String pathOrUrlString = null; if (pathOrUrl instanceof String) { pathOrUrlString = (String) pathOrUrl; } else if (pathOrUrl instanceof CopySource) { pathOrUrlString = ((CopySource) pathOrUrl).getPath(); } if (pathOrUrlString == null) { continue; } commonAncestor = combinePathPrefixes(commonAncestor, pathOrUrlString); } return getPathPrefix(commonAncestor); } private String getPathPrefix(Collection pathsOrUrls, String destPath) { String pathPrefix1 = getPathPrefix(pathsOrUrls); String pathPrefix2 = getPathPrefix(destPath); return combinePathPrefixes(pathPrefix1, pathPrefix2); } private String getPathPrefix(String pathOrUrl1, String pathOrUrl2) { return combinePathPrefixes(getPathPrefix(pathOrUrl1), getPathPrefix(pathOrUrl2)); } private String combinePathPrefixes(String pathPrefix1, String pathPrefix2) { if (pathPrefix1 == null) { return pathPrefix2; } if (pathPrefix2 == null) { return pathPrefix1; } return SVNPathUtil.getCommonPathAncestor(pathPrefix1, pathPrefix2); } private void updateSvnOperationsFactory() { File configDir = this.configDir == null ? null : new File(this.configDir); options = SVNWCUtil.createDefaultOptions(configDir, true); options.setConflictHandler(conflictHandler); authenticationManager = SVNWCUtil.createDefaultAuthenticationManager(configDir, username, password, options.isAuthStorageEnabled()); if (prompt != null) { authenticationManager.setAuthenticationProvider(new JavaHLAuthenticationProvider(prompt)); } else { authenticationManager.setAuthenticationProvider(null); } if (authenticationManager instanceof DefaultSVNAuthenticationManager) { ((DefaultSVNAuthenticationManager) authenticationManager).setRuntimeStorage(getClientCredentialsStorage()); } if (svnOperationFactory != null) { svnOperationFactory.setAuthenticationManager(authenticationManager); svnOperationFactory.setOptions(options); svnOperationFactory.setEventHandler(getEventHandler()); } } static String versionString() { return org.tmatesoft.svn.util.Version.getVersionString(); } static int versionMajor() { return org.tmatesoft.svn.util.Version.getMajorVersion(); } static int versionMinor() { return org.tmatesoft.svn.util.Version.getMinorVersion(); } static int versionMicro() { return org.tmatesoft.svn.util.Version.getMicroVersion(); } @SuppressWarnings("deprecation") static long versionRevisionNumber() { return org.tmatesoft.svn.util.Version.getRevisionNumber(); } private void throwSvnException(Exception e) throws SVNException { //TODO: review SVNErrorMessage errorMessage = SVNErrorMessage.create(SVNErrorCode.UNKNOWN); SVNErrorManager.error(errorMessage, e, SVNLogType.CLIENT); } private void resetLog() { if (progressListener != null) { progressListener.reset(); } } private void beforeOperation() { getEventHandler().setCancelOperation(false); } private void afterOperation() { getEventHandler().setCancelOperation(false); getEventHandler().resetPathPrefix(); resetLog(); } } SVNClientImplVersion.java000066400000000000000000000020741177510526000341050ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17package org.tmatesoft.svn.core.javahl17; import org.apache.subversion.javahl.types.Version; class SVNClientImplVersion extends Version { //TODO: Version class contains more methods, not all of them are present in org.tmatesoft.svn.util.Version private static SVNClientImplVersion instance; public int getMajor() { return SVNClientImpl.versionMajor(); } public int getMinor() { return SVNClientImpl.versionMinor(); } public int getPatch() { return SVNClientImpl.versionMicro(); } public long getRevisionNumber() { return SVNClientImpl.versionRevisionNumber(); } public String toString() { String revision = getRevisionNumber() < 0 ? org.tmatesoft.svn.util.Version.getRevisionString() : Long.toString(getRevisionNumber()); return "SVNKit v" + getMajor() + "." + getMinor() + "." + getPatch() + "." + revision; } public static Version getInstance() { if (instance == null) { instance = new SVNClientImplVersion(); } return instance; } }svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17/SVNReposImpl.java000066400000000000000000000415621177510526000324750ustar00rootroot00000000000000package org.tmatesoft.svn.core.javahl17; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashSet; import java.util.Set; import org.apache.subversion.javahl.ClientException; import org.apache.subversion.javahl.ISVNRepos; import org.apache.subversion.javahl.SubversionException; import org.apache.subversion.javahl.callback.ReposNotifyCallback; import org.apache.subversion.javahl.types.Depth; import org.apache.subversion.javahl.types.Lock; import org.apache.subversion.javahl.types.Revision; import org.apache.subversion.javahl.types.Version; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAction; import org.tmatesoft.svn.core.wc.admin.SVNAdminEventAdapter; import org.tmatesoft.svn.core.wc.admin.SVNUUIDAction; import org.tmatesoft.svn.util.SVNLogType; public class SVNReposImpl { private SVNClientImpl client; private SVNAdminClient svnAdminClient; private boolean cancelOperation; /** * Filesystem in a Berkeley DB */ public static final String BDB = "bdb"; /** * Filesystem in the filesystem */ public static final String FSFS = "fsfs"; public SVNReposImpl() { client = SVNClientImpl.newInstance(); cancelOperation = false; } public void dispose() { client.dispose(); svnAdminClient = null; } public Version getVersion() { return client.getVersion(); } protected SVNAdminClient getAdminClient() { if (svnAdminClient == null) { svnAdminClient = new SVNAdminClient(SVNWCUtil.createDefaultAuthenticationManager(), SVNWCUtil.createDefaultOptions(true)); } return svnAdminClient; } public void create(File path, boolean disableFsyncCommit, boolean keepLog, File configPath, String fstype) throws ClientException { beforeOperation(); if (BDB.equalsIgnoreCase(fstype)) { notImplementedYet("Only " + FSFS + " type of repositories are supported by " + getVersion().toString()); } try { SVNRepositoryFactory.createLocalRepository(path, false, false); if (configPath != null) { } } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } } public void deltify(File path, Revision start, Revision end) throws ClientException { notImplementedYet(); } public void dump(File path, OutputStream dataOut, Revision start, Revision end, boolean incremental, boolean useDeltas, ReposNotifyCallback callback) throws ClientException { dump(path, dataOut, null, start, end, incremental, useDeltas, callback); } public void dump(File path, OutputStream dataOut, final OutputStream errorOut, Revision start, Revision end, boolean incremental, boolean useDeltas, ReposNotifyCallback callback) throws ClientException { beforeOperation(); OutputStream os = dataOut; try { getAdminClient().setEventHandler(new SVNAdminEventAdapter() { @Override public void checkCancelled() throws SVNCancelException { SVNReposImpl.this.checkCancelled(); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (errorOut != null && event.getAction() == SVNAdminEventAction.REVISION_DUMPED) { try { errorOut.write(event.getMessage().getBytes()); errorOut.write(client.getOptions().getNativeEOL()); } catch (IOException e) { } } } }); getAdminClient().doDump(path.getAbsoluteFile(), os, SVNClientImpl.getSVNRevision(start), SVNClientImpl.getSVNRevision(end), incremental, useDeltas); } catch (SVNException e) { try { if (errorOut != null) { errorOut.write(e.getErrorMessage().getFullMessage().getBytes("UTF-8")); errorOut.write(client.getOptions().getNativeEOL()); } } catch (IOException e1) { // } throwException(e, client); } finally { afterOperation(); } } public void hotcopy(File path, File targetPath, boolean cleanLogs) throws ClientException { beforeOperation(); try { getAdminClient().setEventHandler(new SVNAdminEventAdapter() { public void checkCancelled() throws SVNCancelException { SVNReposImpl.this.checkCancelled(); } }); getAdminClient().doHotCopy(path.getAbsoluteFile(), targetPath.getAbsoluteFile()); } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } } public void listDBLogs(File path, ISVNRepos.MessageReceiver receiver) throws ClientException { notImplementedYet("Only " + FSFS + " type of repositories are supported by " + getVersion().toString()); } public void listUnusedDBLogs(File path, ISVNRepos.MessageReceiver receiver) throws ClientException { notImplementedYet("Only " + FSFS + " type of repositories are supported by " + getVersion().toString()); } public void load(File path, InputStream dataInput, boolean ignoreUUID, boolean forceUUID, String relativePath, ReposNotifyCallback callback) throws ClientException { load(path, dataInput, ignoreUUID, forceUUID, false, false, relativePath, callback); } public void load(File path, InputStream dataInput, boolean ignoreUUID, boolean forceUUID, boolean usePreCommitHook, boolean usePostCommitHook, String relativePath, ReposNotifyCallback callback) throws ClientException { load(path, dataInput, null, ignoreUUID, forceUUID, usePreCommitHook, usePostCommitHook, relativePath, callback); } public void load(File path, InputStream dataInput, final OutputStream messageOutput, boolean ignoreUUID, boolean forceUUID, boolean usePreCommitHook, boolean usePostCommitHook, String relativePath, ReposNotifyCallback callback) throws ClientException { beforeOperation(); InputStream is = dataInput; try { SVNUUIDAction uuidAction = SVNUUIDAction.DEFAULT; if (ignoreUUID) { uuidAction = SVNUUIDAction.IGNORE_UUID; } else if (forceUUID) { uuidAction = SVNUUIDAction.FORCE_UUID; } getAdminClient().setEventHandler(new SVNAdminEventAdapter() { private boolean myIsNodeOpened; @Override public void checkCancelled() throws SVNCancelException { SVNReposImpl.this.checkCancelled(); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (messageOutput != null) { try { messageOutput.write(getLoadMessage(event).getBytes("UTF-8")); } catch (IOException e) { } } } protected String getLoadMessage(SVNAdminEvent event) { StringBuffer message = new StringBuffer(); if (event.getAction() != SVNAdminEventAction.REVISION_LOAD && myIsNodeOpened) { message.append(" done."); message.append(client.getOptions().getNativeEOL()); myIsNodeOpened = false; } if (event.getAction() == SVNAdminEventAction.REVISION_LOADED) { message.append(client.getOptions().getNativeEOL()); } message.append(event.getMessage()); message.append(client.getOptions().getNativeEOL()); if (event.getAction() == SVNAdminEventAction.REVISION_LOADED) { message.append(client.getOptions().getNativeEOL()); } myIsNodeOpened = event.getAction() != SVNAdminEventAction.REVISION_LOAD; return message.toString(); } }); getAdminClient().doLoad(path.getAbsoluteFile(), is, usePreCommitHook, usePostCommitHook, uuidAction, relativePath); } catch (SVNException e) { if (messageOutput != null) { try { messageOutput.write(e.getErrorMessage().getFullMessage().getBytes("UTF-8")); messageOutput.write(client.getOptions().getNativeEOL()); } catch (IOException e1) { } } throwException(e, client); } finally { afterOperation(); } } public void lstxns(File path, final ISVNRepos.MessageReceiver receiver) throws ClientException { beforeOperation(); getAdminClient().setEventHandler(new SVNAdminEventAdapter() { @Override public void checkCancelled() throws SVNCancelException { SVNReposImpl.this.checkCancelled(); } public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (receiver != null && event.getTxnName() != null) { receiver.receiveMessageLine(event.getTxnName()); } } }); try { getAdminClient().doListTransactions(path.getAbsoluteFile()); } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } } public long recover(File path, ReposNotifyCallback callback) throws ClientException { beforeOperation(); try { File repositoryRoot = path.getAbsoluteFile(); getAdminClient().doRecover(repositoryRoot); getAdminClient().setEventHandler(new SVNAdminEventAdapter(){ @Override public void checkCancelled() throws SVNCancelException { SVNReposImpl.this.checkCancelled(); } }); return getAdminClient().getYoungestRevision(repositoryRoot); } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } return -1; } public void rmtxns(File path, String[] transactions) throws ClientException { beforeOperation(); try { getAdminClient().setEventHandler(new SVNAdminEventAdapter() { @Override public void checkCancelled() throws SVNCancelException { SVNReposImpl.this.checkCancelled(); } }); getAdminClient().doRemoveTransactions(path.getAbsoluteFile(), transactions); } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } } public void setRevProp(File path, Revision rev, String propName, String propValue, boolean usePreRevPropChangeHook, boolean usePostRevPropChangeHook) throws SubversionException { beforeOperation(); try { setRevisionProperty(path, rev, propName, propValue, !usePreRevPropChangeHook, !usePostRevPropChangeHook); } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } } public void verify(File path, Revision start, Revision end, ReposNotifyCallback callback) throws ClientException { verify(path, null, start, end, callback); } public void verify(File path, final OutputStream messageOut, Revision start, Revision end, ReposNotifyCallback callback) throws ClientException { beforeOperation(); try { getAdminClient().setEventHandler(new SVNAdminEventAdapter() { public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (messageOut != null && event.getAction() == SVNAdminEventAction.REVISION_DUMPED) { try { messageOut.write(event.getMessage().getBytes()); messageOut.write(client.getOptions().getNativeEOL()); } catch (IOException e) { } } } }); getAdminClient().doVerify(path.getAbsoluteFile(), SVNClientImpl.getSVNRevision(start), SVNClientImpl.getSVNRevision(end)); } catch (SVNException e) { try { if (messageOut != null) { messageOut.write(e.getErrorMessage().getFullMessage().getBytes("UTF-8")); messageOut.write(client.getOptions().getNativeEOL()); } } catch (IOException e1) { // } throwException(e, client); } finally { afterOperation(); } } public Set lslocks(File path, Depth depth) throws ClientException { beforeOperation(); final Set locks = new HashSet(); getAdminClient().setEventHandler(new SVNAdminEventAdapter() { public void handleAdminEvent(SVNAdminEvent event, double progress) throws SVNException { if (event.getAction() == SVNAdminEventAction.LOCK_LISTED) { SVNLock svnLock = event.getLock(); Lock lock = SVNClientImpl.getLock(svnLock); locks.add(lock); } } }); try { getAdminClient().doListLocks(path.getAbsoluteFile()); } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } return locks; } public void rmlocks(File path, String[] locks) throws ClientException { beforeOperation(); try { getAdminClient().doRemoveLocks(path.getAbsoluteFile(), locks); } catch (SVNException e) { throwException(e, client); } finally { afterOperation(); } } public void upgrade(File path, ReposNotifyCallback callback) throws ClientException { notImplementedYet(); } public void pack(File path, ReposNotifyCallback callback) throws ClientException { notImplementedYet(); } public void cancelOperation() throws ClientException { cancelOperation = true; } private void checkCancelled() throws SVNCancelException { if (cancelOperation) { cancelOperation = false; SVNErrorManager.cancel("operation cancelled", SVNLogType.DEFAULT); } } private static void setRevisionProperty(File path, Revision rev, String propName, String propValue, boolean bypassPreRevPropChangeHook, boolean bypassPostRevPropChangeHook) throws SVNException { SVNRepository repository = SVNRepositoryFactory.create(SVNURL.fromFile(path.getAbsoluteFile())); ((FSRepository) repository).setRevisionPropertyValue(SVNClientImpl.getSVNRevision(rev).getNumber(), propName, SVNPropertyValue.create(propValue), bypassPreRevPropChangeHook, bypassPostRevPropChangeHook); } private void notImplementedYet() throws ClientException { notImplementedYet(null); } private void notImplementedYet(String message) throws ClientException { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, message == null ? "Requested SVNAdmin functionality is not yet implemented" : message); throwException(new SVNException(err), client); } public static void throwException(SVNException e, SVNClientImpl svnClient) throws ClientException { ClientException ec = SVNClientImpl.getClientException(e); ec.initCause(e); svnClient.getDebugLog().logFine(SVNLogType.DEFAULT, ec); svnClient.getDebugLog().logFine(SVNLogType.DEFAULT, e); throw ec; } private void beforeOperation() { cancelOperation = false; } private void afterOperation() { cancelOperation = false; getAdminClient().setEventHandler(null); } } UserPasswordSSHCallback.java000066400000000000000000000006161177510526000345440ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17package org.tmatesoft.svn.core.javahl17; import org.apache.subversion.javahl.callback.UserPasswordCallback; public interface UserPasswordSSHCallback extends UserPasswordCallback { public boolean promptSSH(String realm, String username, int sshPort, boolean maySave); public String getSSHPrivateKeyPath(); public String getSSHPrivateKeyPassphrase(); public int getSSHPort(); } UserPasswordSSLCallback.java000066400000000000000000000005201177510526000345420ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-javahl16/src/main/java/org/tmatesoft/svn/core/javahl17package org.tmatesoft.svn.core.javahl17; import org.apache.subversion.javahl.callback.UserPasswordCallback; public interface UserPasswordSSLCallback extends UserPasswordCallback { public boolean promptSSL(String realm, boolean maySave); public String getSSLClientCertPath(); public String getSSLClientCertPassword(); } svnkit-1.7.5+dfsg/svnkit-osgi/000077500000000000000000000000001177510526000162425ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/build.gradle000066400000000000000000000036201177510526000205220ustar00rootroot00000000000000apply plugin: 'osgi' project.ext { bundleName = rootProject.group bundleSymbolicName = 'SVNKit pure Java Subversion Library' bundleVersion = buildVersion.getFullOSGIVersion() bundleVendor = 'TMate Software' } configurations { embedOsgi } dependencies { compile project(path: ':svnkit') compile project(path: ':svnkit-javahl16') compile 'org.eclipse.core:runtime:3.2.0-v20060603' embedOsgi project(path: ':svnkit', transitive: false, configuration: 'archives') embedOsgi project(path: ':svnkit-javahl16', transitive: false, configuration: 'archives') embedOsgi 'de.regnis.q.sequence:sequence-library:1.0.2' } classes << { configurations.embedOsgi.files.each { f -> if (f.name.endsWith('.jar') || f.name.endsWith('.zip')) { copy { into 'build/classes/main' from zipTree(f) exclude 'META-INF/**' } } } } jar { baseName = bundleName manifest { attributes 'Bundle-SymbolicName': bundleName, 'Bundle-Version': bundleVersion, 'Bundle-Vendor': bundleVendor, 'Bundle-Name': bundleSymbolicName, 'Bundle-RequiredExecutionEnvironment' : 'J2SE-' + targetCompatibility, 'Bundle-Activator' : 'org.tmatesoft.svn.core.SVNKitActivator', 'Bundle-ActivationPolicy' : 'lazy', 'Eclipse-BundleShape' : 'jar', 'Require-Bundle': 'net.java.dev.jna;bundle-version="[3.2.7,4.0.0)";resolution:=optional,' + 'com.trilead.ssh2;bundle-version="[1.0.0,2.0.0)",' + 'org.tmatesoft.sqljet;bundle-version="[1.0.5,2.0.0)",' + 'org.eclipse.core.runtime;bundle-version="[3.0.0,4.0.0)"' instruction 'Export-Package', '*;version=' + bundleVersion instruction 'Import-Package', '!*' } } uploadMaven { repositories.mavenDeployer { pom.whenConfigured { p -> p.dependencies.clear() } } }svnkit-1.7.5+dfsg/svnkit-osgi/src/000077500000000000000000000000001177510526000170315ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/000077500000000000000000000000001177510526000177555ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/000077500000000000000000000000001177510526000206765ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/000077500000000000000000000000001177510526000214655ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/000077500000000000000000000000001177510526000234735ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/svn/000077500000000000000000000000001177510526000243015ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/svn/core/000077500000000000000000000000001177510526000252315ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/svn/core/SVNKitActivator.java000066400000000000000000000060151177510526000310710ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core; import org.eclipse.osgi.framework.log.FrameworkLog; import org.eclipse.osgi.framework.log.FrameworkLogEntry; import org.eclipse.osgi.service.debug.DebugOptions; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; import org.tmatesoft.svn.core.internal.io.svn.SVNSSHConnector; import org.tmatesoft.svn.util.ISVNDebugLog; import org.tmatesoft.svn.util.SVNDebugLog; /** * @version 1.1.2 * @author TMate Software Ltd. */ public class SVNKitActivator implements BundleActivator { private ServiceTracker myDebugTracker = null; private ServiceTracker myFLogTracker = null; private String myPluginID; public void start(BundleContext context) throws Exception { myPluginID = context.getBundle().getSymbolicName(); myDebugTracker = new ServiceTracker(context, DebugOptions.class.getName(), null); myDebugTracker.open(); myFLogTracker = new ServiceTracker(context, FrameworkLog.class.getName(), null); myFLogTracker.open(); ISVNDebugLog debugLog = new SVNKitLog(this); SVNDebugLog.setDefaultLog(debugLog); } public boolean getDebugOption(String option) { if (myDebugTracker == null) { return false; } DebugOptions options = (DebugOptions) myDebugTracker.getService(); if (options != null) { option = myPluginID + option; String value = options.getOption(option); return "true".equalsIgnoreCase(value); } return false; } public FrameworkLogEntry createFrameworkLogEntry(int level, String message, Throwable th) { return new FrameworkLogEntry(myPluginID, level, 0, message, 0, th, null); } public FrameworkLog getFrameworkLog() { if (myFLogTracker == null) { return null; } FrameworkLog log = (FrameworkLog) myFLogTracker.getService(); if (log != null) { return log; } return null; } public void stop(BundleContext context) throws Exception { SVNSSHConnector.shutdown(); try { if (myDebugTracker != null) { myDebugTracker.close(); } } finally { myDebugTracker = null; } try { if (myFLogTracker != null) { myFLogTracker.close(); } } finally { myFLogTracker = null; } } } svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/svn/core/SVNKitLog.java000066400000000000000000000142041177510526000276550ustar00rootroot00000000000000/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import org.eclipse.osgi.framework.log.FrameworkLog; import org.eclipse.osgi.framework.log.FrameworkLogEntry; import org.osgi.framework.FrameworkEvent; import org.tmatesoft.svn.util.SVNDebugLogAdapter; import org.tmatesoft.svn.util.SVNLogType; /** * @author TMate Software Ltd. * @version 1.3 */ public class SVNKitLog extends SVNDebugLogAdapter { private static final String DEBUG_FINE = "/debug/fine"; private static final String DEBUG_INFO = "/debug/info"; private static final String DEBUG_WARNING = "/debug/warning"; private static final String DEBUG_ERROR = "/debug/error"; private static final String DEBUG_TRACE = "/debug/trace"; private SVNKitActivator myActivator; public SVNKitLog(SVNKitActivator activator) { myActivator = activator; } public boolean isFineEnabled() { return myActivator.getDebugOption(DEBUG_FINE); } public boolean isInfoEnabled() { return myActivator.getDebugOption(DEBUG_INFO); } public boolean isWarningEnabled() { return myActivator.getDebugOption(DEBUG_WARNING); } public boolean isErrorEnabled() { return myActivator.getDebugOption(DEBUG_ERROR); } public boolean isTraceEnabled() { return myActivator.getDebugOption(DEBUG_TRACE); } public InputStream createLogStream(SVNLogType logType, InputStream is) { if (isTraceEnabled()) { return super.createLogStream(logType, is); } return is; } public OutputStream createLogStream(SVNLogType logType, OutputStream os) { if (isTraceEnabled()) { return super.createLogStream(logType, os); } return os; } public void logFinest(SVNLogType logType, Throwable th) { log(logType, th, Level.FINEST); } public void logFinest(SVNLogType logType, String message) { log(logType, message, Level.FINEST); } public void logFiner(SVNLogType logType, Throwable th) { log(logType, th, Level.FINE); } public void logFiner(SVNLogType logType, String message) { log(logType, message, Level.FINE); } public void logFine(SVNLogType logType, Throwable th) { log(logType, th, Level.INFO); } public void logFine(SVNLogType logType, String message) { log(logType, message, Level.INFO); } public void logError(SVNLogType logType, String message) { log(logType, message, Level.WARNING); } public void logError(SVNLogType logType, Throwable th) { log(logType, th, Level.WARNING); } public void logSevere(SVNLogType logType, String message) { log(logType, message, Level.SEVERE); } public void logSevere(SVNLogType logType, Throwable th) { log(logType, th, Level.SEVERE); } public void log(SVNLogType logType, String message, byte[] data) { FrameworkLog log = myActivator.getFrameworkLog(); if (log == null) { return; } if (isTraceEnabled()) { FrameworkLogEntry entry = null; String dataMessage = null; try { dataMessage = new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { dataMessage = new String(data); } message += " : " + dataMessage; message = getMessage(logType, message); entry = myActivator.createFrameworkLogEntry(FrameworkEvent.INFO, message, null); if (entry != null) { log.log(entry); } } } public void log(SVNLogType logType, Throwable th, Level logLevel) { FrameworkLog log = myActivator.getFrameworkLog(); if (log == null) { return; } if (th != null) { int level = getSeverity(logLevel); if (level >= 0) { String message = getMessage(logType, th.getMessage()); FrameworkLogEntry entry = myActivator.createFrameworkLogEntry(FrameworkEvent.ERROR, message, th); if (entry != null) { log.log(entry); } } } } public void log(SVNLogType logType, String message, Level logLevel) { FrameworkLog log = myActivator.getFrameworkLog(); if (log == null) { return; } if (message != null) { int level = getSeverity(logLevel); if (level >= 0) { message = getMessage(logType, message); FrameworkLogEntry entry = myActivator.createFrameworkLogEntry(FrameworkEvent.ERROR, message, null); if (entry != null) { log.log(entry); } } } } private int getSeverity(Level logLevel) { int level = -1; if ((logLevel == Level.FINEST || logLevel == Level.FINE) && isFineEnabled()) { level = FrameworkEvent.INFO; } else if (logLevel == Level.INFO && isInfoEnabled()) { level = FrameworkEvent.INFO; } else if (logLevel == Level.WARNING && isWarningEnabled()) { level = FrameworkEvent.WARNING; } else if (logLevel == Level.SEVERE && isErrorEnabled()) { level = FrameworkEvent.ERROR; } return level; } private String getMessage(SVNLogType logType, String originalMessage) { if (originalMessage == null) { return logType.getName(); } return logType.getShortName() + ": " + originalMessage; } } svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/svn/core/internal/000077500000000000000000000000001177510526000270455ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/svn/core/internal/wc/000077500000000000000000000000001177510526000274565ustar00rootroot00000000000000EclipseSVNAuthenticationManager.java000066400000000000000000000215551177510526000364200ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-osgi/src/main/java/org/tmatesoft/svn/core/internal/wc/* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.auth.SVNSSHAuthentication; import org.tmatesoft.svn.core.auth.SVNSSLAuthentication; import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication; import org.tmatesoft.svn.core.internal.util.SVNHashMap; /** * @version 1.3 * @author TMate Software Ltd. */ public class EclipseSVNAuthenticationManager extends DefaultSVNAuthenticationManager { private static URL DEFAULT_URL; static { try { DEFAULT_URL = new URL("http://tmate.org/svn/"); } catch (MalformedURLException e) { } } public EclipseSVNAuthenticationManager(File configDirectory, boolean storeAuth, String userName, String password, File keyFile, String passphrase) { super(configDirectory, storeAuth, userName, password, keyFile, passphrase); } protected ISVNAuthenticationProvider createCacheAuthenticationProvider(File authDir, String userName) { return new KeyringAuthenticationProvider(); } protected ISVNAuthenticationProvider createDefaultAuthenticationProvider(String userName, String password, File privateKey, String passphrase, boolean allowSave) { return new DumbAuthenticationProvider(userName, password, privateKey, passphrase, allowSave) { public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) { return ACCEPTED; } }; } static class KeyringAuthenticationProvider implements ISVNAuthenticationProvider, ISVNPersistentAuthenticationProvider { public KeyringAuthenticationProvider() { } public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) { // get from key-ring, use realm. realm = realm == null ? DEFAULT_URL.toString() : realm; Map info = Platform.getAuthorizationInfo(DEFAULT_URL, realm, kind); // convert info to SVNAuthentication. if (info != null && ISVNAuthenticationManager.SSL.equals(kind)) { String sslKind = (String) info.get("ssl-kind"); if (sslKind != null && SVNSSLAuthentication.MSCAPI.equals(sslKind)) { String alias = (String) info.get("alias"); return new SVNSSLAuthentication(sslKind, alias, authMayBeStored, url, false); } String password = (String) info.get("password"); if (SVNSSLAuthentication.isCertificatePath(realm)) { if (password != null) { return new SVNPasswordAuthentication("", password, authMayBeStored, url, false); } } else { String path = (String) info.get("cert"); if (path != null) { SVNSSLAuthentication auth = new SVNSSLAuthentication(new File(path), password, authMayBeStored, url, false); auth.setCertificatePath(path); return auth; } } } else if (info != null && !info.isEmpty() && info.get("username") != null) { if (ISVNAuthenticationManager.PASSWORD.equals(kind)) { return new SVNPasswordAuthentication((String) info.get("username"), (String) info.get("password"), authMayBeStored, url, false); } else if (ISVNAuthenticationManager.SSH.equals(kind)) { int port = url.hasPort() ? url.getPort() : -1; if (port < 0 && info.get("port") != null) { port = Integer.parseInt((String) info.get("port")); } if (port < 0) { // will give us default port. port = url.getPort(); } if (info.get("key") != null) { File keyPath = new File((String) info.get("key")); return new SVNSSHAuthentication((String) info.get("username"), keyPath, (String) info.get("passphrase"), port, authMayBeStored, url, false); } else if (info.get("password") != null) { return new SVNSSHAuthentication((String) info.get("username"), (String) info.get("password"), port, authMayBeStored, url, false); } } else if (ISVNAuthenticationManager.USERNAME.equals(kind)) { return new SVNUserNameAuthentication((String) info.get("username"), authMayBeStored, url, false); } } return null; } public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) { return ACCEPTED_TEMPORARY; } public void saveAuthentication(SVNAuthentication auth, String kind, String realm) { if (!(auth instanceof SVNSSLAuthentication) && (auth.getUserName() == null || "".equals(auth.getUserName()))) { return; } realm = realm == null ? DEFAULT_URL.toString() : realm; Map info = new SVNHashMap(); // convert info to SVNAuthentication. info.put("username", auth.getUserName()); if (auth instanceof SVNPasswordAuthentication) { info.put("password", ((SVNPasswordAuthentication) auth).getPassword()); } else if (auth instanceof SVNSSHAuthentication) { SVNSSHAuthentication sshAuth = (SVNSSHAuthentication) auth; if (sshAuth.getPrivateKeyFile() != null) { info.put("key", sshAuth.getPrivateKeyFile().getAbsolutePath()); if (sshAuth.getPassphrase() != null) { info.put("passphrase", sshAuth.getPassphrase()); } } else if (sshAuth.getPassword() != null) { info.put("password", sshAuth.getPassword()); } if (sshAuth.getPortNumber() >= 0) { info.put("port", Integer.toString(sshAuth.getPortNumber())); } } else if (auth instanceof SVNSSLAuthentication) { SVNSSLAuthentication sslAuth = (SVNSSLAuthentication) auth; String password = sslAuth.getPassword(); if (password != null && !"".equals(password)) { info.put("password", password); } if (SVNSSLAuthentication.SSL.equals(sslAuth.getSSLKind())) { String path = sslAuth.getCertificatePath(); if (path != null) { info.put("cert", path); } } else if (SVNSSLAuthentication.MSCAPI.equals(sslAuth.getSSLKind())) { info.put("ssl-kind", sslAuth.getSSLKind()); info.put("alias", sslAuth.getAlias()); } } try { Platform.addAuthorizationInfo(DEFAULT_URL, realm, kind, info); } catch (CoreException e) { } } public byte[] loadFingerprints(String realm) { Map info = Platform.getAuthorizationInfo(DEFAULT_URL, realm, "svn.ssh.server"); if (info != null && realm.equals(info.get("svn:realmstring"))) { return (byte[]) info.get("hostkey"); } return null; } public void saveFingerprints(String realm, byte[] fingerprints) { Map info = new SVNHashMap(); info.put("svn:realmstring", realm); info.put("hostkey", fingerprints); try { Platform.addAuthorizationInfo(DEFAULT_URL, realm, "svn.ssh.server", info); } catch (CoreException e) { } } } } svnkit-1.7.5+dfsg/svnkit-test/000077500000000000000000000000001177510526000162605ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/build.gradle000066400000000000000000000170531177510526000205450ustar00rootroot00000000000000configurations { pythonTests16 svnBinaries16 pythonTests17 svnBinaries17 } dependencies { pythonTests16 'org.tigris.subversion:svn-python-tests:1.6.18-v2@tgz' if (!project.hasProperty('svn.binaries.local')) { svnBinaries16 'org.tigris.subversion:svn-binaries:1.6.18-v2@tgz' } pythonTests17 'org.apache.subversion:svn-python-tests:1.7.5@tgz' if (!project.hasProperty('svn.binaries.local')) { svnBinaries17 'org.apache.subversion:svn-binaries:1.7.5@tgz' } } sourceSets { main { java { srcDir file('nailgun/src/java/prod') } } } project.ext { sandboxDir = getSandboxLocation() logsDir = new File(sandboxDir, 'logs') svnBinariesDir = getSvnBinariesLocation() pythonTestsDir = new File(sandboxDir, 'svn-python-tests') testPropertiesFile = new File(sandboxDir, 'test.properties') svnVersion = project.hasProperty('svnVersion') ? project.getProperty('svnVersion') : '16' singleFormat = project.hasProperty('singleFormat') testConfiguration = project.hasProperty('testConfiguration') ? project.getProperty('testConfiguration') : 'default' } test.dependsOn configurations."pythonTests${project.svnVersion}" test.dependsOn configurations."svnBinaries${project.svnVersion}" classes << { copy { into file('build/classes/main') from file('nailgun/src/java/prod') include '**/*.properties' } } test { ignoreFailures = true } test.doFirst { project.mkdir(sandboxDir) project.mkdir(logsDir) buildNailgun() // create wc.h file at build/libsvn_wc/wc.h File wcHeader = new File(buildDir, "libsvn_wc/wc.h"); wcHeader.getParentFile().mkdirs(); wcHeader << "\n#define SVN_WC__VERSION 29\n"; try { runPythonTests() } finally { cleanSandbox() } } def runPythonTests() { File pythonTestsTar = configurations."pythonTests${project.svnVersion}".files.find {return true} File svnBinariesTar = configurations."svnBinaries${project.svnVersion}".files.find {return true} untar(pythonTestsTar, sandboxDir) copy { into sandboxDir into('svn-python-tests') { from 'configurations/svn' + project.svnVersion + '/cmdline' } } if (!project.hasProperty('svn.binaries.local')) { untar(svnBinariesTar, sandboxDir) } if (getOSName() != 'windows' && project.svnVersion == '17') { File link = new File(sandboxDir, 'svn-python-tests/entries-dump') File target = new File(svnBinariesDir, 'bin/entries-dump') if (!link.exists() && target.exists()) { ant.symlink(link: link.absolutePath, resource: target.absolutePath) } File libSvnWc = new File(sandboxDir, "libsvn_wc"); libSvnWc.mkdirs(); link = new File(libSvnWc, 'wc-lock-tester') target = new File(svnBinariesDir, 'bin/wc-lock-tester') if (!link.exists() && target.exists()) { ant.symlink(link: link.absolutePath, resource: target.absolutePath) } } copy { into sandboxDir into('') { from "configurations/shared" } into('') { from "configurations/svn${project.svnVersion}" exclude "**/*.properties" } } if (svnBinariesDir == null || !svnBinariesDir.isDirectory()) { println "Cannot locate subversion binaries for '${getOSName()}' OS, skipping python tests." return } if (getOSName() != 'windows') { exec { commandLine 'ldd' args new File(svnBinariesDir, 'bin/svn').absolutePath environment 'LD_LIBRARY_PATH' : new File(svnBinariesDir, 'lib').absolutePath } } exec { commandLine new File(svnBinariesDir, 'bin/svn').absolutePath args '--version' environment 'LD_LIBRARY_PATH' : new File(svnBinariesDir, 'lib').absolutePath } // 2. generate test environment properties and merge them with the test properties def testProperties = generateTestEnvironmentProperties(svnBinariesDir) appendDefaultTestProperties(project.svnVersion, project.testConfiguration, testProperties) testPropertiesFile.withOutputStream { stream -> testProperties.save(stream, null) } javaexec { if (project.hasProperty('debug')) { debug = true } workingDir = sandboxDir enableAssertions = true systemProperty 'sun.io.useCanonCaches', 'false' systemProperty 'svnkit.compatibleHash', 'true' systemProperty 'svnkit.wc.17', (project.svnVersion == '17') systemProperty 'svnkit.wc.17only', project.singleFormat environment 'LD_LIBRARY_PATH' : new File(svnBinariesDir, 'lib').absolutePath main = 'org.tmatesoft.svn.core.test.PythonTests' classpath = sourceSets.main.runtimeClasspath args testPropertiesFile.absolutePath, new File(sandboxDir, 'daemon').absolutePath } } def appendDefaultTestProperties(String svnVersion, String configurationName, Properties properties) { File propertiesFile = file("configurations/svn${svnVersion}/${configurationName}.properties") propertiesFile.withInputStream { properties.load(it) } return properties } def generateTestEnvironmentProperties(File svnBinaries) { Properties properties = new Properties() properties.put('daemon', 'true') properties.put('svn.home', svnBinariesDir.absolutePath ) properties.put('svnserve.path', new File(svnBinaries, 'bin/svnserve').absolutePath ) properties.put('apache.path', '/usr/sbin/apache2ctl') properties.put('apache.root', '/usr/lib/apache2') properties.put('apache.svn.modules', new File(svnBinaries, 'modules').absolutePath ) properties.put('python.launcher', 'python') properties.put('python.tests', pythonTestsDir.absolutePath ) properties.put('python.tests.results', testResultsDir.absolutePath) properties.put('python.tests.logDir', logsDir.absolutePath) return properties } def untar(File tgz, File into) { if (getOSName() != 'windows') { exec { commandLine 'tar' args '-C', into.absolutePath, '-xzf', tgz.absolutePath } } else { ant.untar(src: tgz.absolutePath, dest: into.absolutePath, compression: 'gzip') } } def buildNailgun() { copy { from file('nailgun') into new File(sandboxDir, 'daemon') include '**/ng.exe' include 'src/**' include 'Makefile' } if (getOSName() != 'windows') { exec { commandLine 'make' args 'ng' workingDir = new File(sandboxDir, 'daemon') } } } def getOSName() { String osNameProperty = System.getProperty('os.name') osNameProperty = osNameProperty.toLowerCase() if (osNameProperty.indexOf('windows') >= 0) { return 'windows' } else if (osNameProperty.indexOf('mac') >= 0) { return 'osx' } return 'linux' } def getSvnBinariesLocation() { if (System.getenv()['SVN_TEST_HOME'] != null) { return new File(System.getenv()['SVN_TEST_HOME']) } return new File(sandboxDir, 'svn-binaries/' + getOSName()) } def getSandboxLocation() { String systemLocation = System.getenv()['SVN_TEST_SANDBOX']; if (systemLocation != null) { File sandbox = File.createTempFile('svnkit.', '.sandbox', new File(systemLocation)) sandbox.delete() return sandbox } return new File(buildDir, 'sandbox') } def cleanSandbox() { String systemLocation = System.getenv()['SVN_TEST_SANDBOX']; if (systemLocation != null) { project.delete(sandboxDir.absolutePath) } } svnkit-1.7.5+dfsg/svnkit-test/configurations/000077500000000000000000000000001177510526000213125ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/000077500000000000000000000000001177510526000225605ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/apache/000077500000000000000000000000001177510526000240015ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/apache/python.template.conf000066400000000000000000000036421177510526000300100ustar00rootroot00000000000000ServerRoot "%root%" PidFile "%home%/httpd.%port%.pid" Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 300 ThreadsPerChild 100 MaxRequestsPerChild 10000 Listen %port% LoadModule alias_module "%root%/modules/mod_alias.so" LoadModule auth_basic_module "%root%/modules/mod_auth_basic.so" LoadModule authn_file_module "%root%/modules/mod_authn_file.so" LoadModule authz_default_module "%root%/modules/mod_authz_default.so" LoadModule authz_groupfile_module "%root%/modules/mod_authz_groupfile.so" LoadModule authz_host_module "%root%/modules/mod_authz_host.so" LoadModule authz_user_module "%root%/modules/mod_authz_user.so" LoadModule authn_anon_module "%root%/modules/mod_authn_anon.so" LoadModule auth_digest_module "%root%/modules/mod_auth_digest.so" LoadModule dav_module "%root%/modules/mod_dav.so" LoadModule deflate_module "%root%/modules/mod_deflate.so" LoadModule dav_svn_module "%apache.svn.modules%/mod_dav_svn.so" LoadModule authz_svn_module "%apache.svn.modules%/mod_authz_svn.so" ServerName localhost:%port% UseCanonicalName Off HostnameLookups Off LogLevel emerg ErrorLog "%home%/httpd.%port%.error.log" DAV svn SetOutputFilter DEFLATE SVNParentPath "%python.tests%/svn-test-work/repositories" AuthzSVNAccessFile "%python.tests%/svn-test-work/authz" Require valid-user AuthType Basic AuthName "Subversion Repository" AuthUserFile "%python.tests%/../apache/users" %apache.options% DAV svn SetOutputFilter DEFLATE SVNPath "%python.tests%/svn-test-work/local_tmp/repos" AuthzSVNAccessFile "%python.tests%/svn-test-work/authz" Require valid-user AuthType Basic AuthName "Subversion Repository" AuthUserFile "%python.tests%/../apache/users" %apache.options% svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/apache/users000066400000000000000000000001361177510526000250650ustar00rootroot00000000000000jrandom:$apr1$mO1.....$JTuE4Grurai/OnYEvR7xR/ jconstant:$apr1$mO1.....$JTuE4Grurai/OnYEvR7xR/ svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/daemon/000077500000000000000000000000001177510526000240235ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/daemon/matcher.pl000077500000000000000000000002561177510526000260110ustar00rootroot00000000000000#!/usr/bin/perl my $command_line = ""; foreach $argnum (0 .. $#ARGV) { $command_line .= "'@ARGV[$argnum]' "; } if ($command_line =~ m/%pattern%/) { exit 0; } exit 1; svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/daemon/snapshot000077500000000000000000000004051177510526000256070ustar00rootroot00000000000000#!/bin/bash export GIT_AUTHOR_NAME="Mortimer Adler" export GIT_COMMITTER_NAME="Mortimer Adler" git init $1 pushd $1 cat commit_msg >> commits_log git init git add -A git commit -F commit_msg tag=`wc -l < commits_log` git tag -a "$tag" -m "$tag" popd exit 0 svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/daemon/template000077500000000000000000000011171177510526000255640ustar00rootroot00000000000000#!/bin/bash snapshot() { if [ -x $dir/snapshot ] then echo "$@" > "%svn_test_work%/commit_msg" $dir/snapshot "%svn_test_work%" > /dev/null 2> /dev/null fi } dir=`dirname $0` scriptname=`basename $0` if [ -x $dir/matcher.pl ] then # only run jsvn if matched $dir/matcher.pl "$@" if [ $? -ne 0 ] then # run native %svn_home%/bin/%name% "$@" < /dev/stdin sr=$? snapshot $scriptname "$@" exit $sr fi fi NG_MAINCLASS=%mainclass% NG_PORT=%port% %NG% $NG_MAINCLASS --nailgun-port $NG_PORT %name% "$@" sr=$? snapshot $scriptname "$@" exit $sr svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/daemon/template.bat000066400000000000000000000000451177510526000263250ustar00rootroot00000000000000@echo off python %~dp0/j%name%.py %*svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/daemon/template.py000066400000000000000000000007571177510526000262210ustar00rootroot00000000000000#!/usr/bin/env python import sys, string, re, os, getopt, stat, subprocess line = string.join(sys.argv[1:]) p = re.compile('%pattern%') m = p.match(line) allargs=[] if (m): allargs.append('ng.exe') allargs.append('%mainclass%') allargs.append('--nailgun-port') allargs.append('%port%') allargs.append('%name%') else: allargs.append('%svn_home%/bin/%name%') allargs.extend(sys.argv[1:]) p = subprocess.Popen(allargs, shell=True, close_fds=True) p.communicate() sys.exit(p.returncode)svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/fsfs.conf000066400000000000000000000036011177510526000243700ustar00rootroot00000000000000### This file controls the configuration of the FSFS filesystem. [memcached-servers] ### These options name memcached servers used to cache internal FSFS ### data. See http://www.danga.com/memcached/ for more information on ### memcached. To use memcached with FSFS, run one or more memcached ### servers, and specify each of them as an option like so: # first-server = 127.0.0.1:11211 # remote-memcached = mymemcached.corp.example.com:11212 ### The option name is ignored; the value is of the form HOST:PORT. ### memcached servers can be shared between multiple repositories; ### however, if you do this, you *must* ensure that repositories have ### distinct UUIDs and paths, or else cached data from one repository ### might be used by another accidentally. Note also that memcached has ### no authentication for reads or writes, so you must ensure that your ### memcached servers are only accessible by trusted users. [caches] ### When a cache-related error occurs, normally Subversion ignores it ### and continues, logging an error if the server is appropriately ### configured (and ignoring it with file:// access). To make ### Subversion never ignore cache errors, uncomment this line. # fail-stop = true [rep-sharing] ### To conserve space, the filesystem can optionally avoid storing ### duplicate representations. This comes at a slight cost in performace, ### as maintaining a database of shared representations can increase ### commit times. The space savings are dependent upon the size of the ### repository, the number of objects it contains and the amount of ### duplication between them, usually a function of the branching and ### merging process. ### ### The following parameter enables rep-sharing in the repository. It can ### be switched on and off at will, but for best space-saving results ### should be enabled consistently over the life of the repository. ### enable-rep-sharing = true svnkit-1.7.5+dfsg/svnkit-test/configurations/shared/python-suite.txt000066400000000000000000000006611177510526000257740ustar00rootroot00000000000000authz ALL autoprop ALL basic ALL blame ALL cat ALL changelist ALL checkout ALL commit ALL copy ALL depth ALL diff ALL export ALL externals ALL history ALL import ALL info ALL lock ALL log ALL merge ALL -4 merge_authz ALL mergeinfo ALL prop ALL resolved ALL revert ALL schedule ALL special ALL stat ALL svnadmin ALL -8 -9 svnlook ALL -11 svnsync ALL svndumpfilter ALL svnversion ALL switch ALL trans ALL tree_conflict ALL update ALL svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/000077500000000000000000000000001177510526000222675ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/all.properties000066400000000000000000000000621177510526000251530ustar00rootroot00000000000000python.http=true python.svn=true python.file=true svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/basic.properties000066400000000000000000000001131177510526000254610ustar00rootroot00000000000000python.tests.suite=basic python.http=true python.svn=true python.file=true svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/dav.nobulk.properties000066400000000000000000000001341177510526000264460ustar00rootroot00000000000000apache.options=SVNAllowBulkUpdates Off python.http=true python.svn=false python.file=false svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/dav.properties000066400000000000000000000000641177510526000251570ustar00rootroot00000000000000python.http=true python.svn=false python.file=false svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/default.properties000066400000000000000000000001301177510526000260230ustar00rootroot00000000000000logAll=true python.tests.suite=log 26 python.http=true python.svn=true python.file=true svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/fsfs.properties000066400000000000000000000000641177510526000253460ustar00rootroot00000000000000python.http=false python.svn=false python.file=true svnkit-1.7.5+dfsg/svnkit-test/configurations/svn16/svn.properties000066400000000000000000000000641177510526000252130ustar00rootroot00000000000000python.http=false python.svn=true python.file=false svnkit-1.7.5+dfsg/svnkit-test/configurations/svn17/000077500000000000000000000000001177510526000222705ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/svn17/all.properties000066400000000000000000000015551177510526000251640ustar00rootroot00000000000000python.tests.suite=upgrade,import,basic,changelist,resolve,resolved,stat,checkout,update,commit,relocate,switch,externals,export,schedule,revert,prop,cat,history,log,lock,copy,blame,depth,mergeinfo,merge,merge_reintegrate,merge_tree_conflict,merge_authz,info,tree_conflict,trans,autoprop,special,authz,diff python.http=true python.svn=true python.file=true python.tests.sleepy=(diff_tests.py_21)|(stat_tests.py_22)|(diff_tests.py_60) python.tests.listOption=--list python.tests.pattern=(^|'-m'\\s'[^']*'\\s)'(di|diff|merge|upgrade|mergeinfo|list|ls|mkdir|resolve|resolved|cleanup|import|changelist|cl|blame|praise|annotate|ann|copy|cp|move|mv|rename|ren|lock|unlock|log|cat|ps|pset|propset|pd|pdel|propdel|pe|propedit|revert|rm|del|remove|delete|add|export|st|stat|status|co|checkout|up|update|ci|commit|info|pg|pget|propget|pl|plist|proplist|relocate|sw|switch)'\\s(.|\\n)*$svnkit-1.7.5+dfsg/svnkit-test/configurations/svn17/basic.properties000066400000000000000000000007761177510526000255010ustar00rootroot00000000000000python.tests.suite=basic python.http=true python.svn=true python.file=true python.tests.listOption=--list python.tests.pattern=(^|'-m'\\s'[^']*'\\s)'(merge|upgrade|mergeinfo|list|ls|mkdir|resolve|resolved|cleanup|import|changelist|cl|blame|praise|annotate|ann|copy|cp|move|mv|rename|ren|lock|unlock|log|cat|ps|pset|propset|pd|pdel|propdel|pe|propedit|revert|rm|del|remove|delete|add|export|st|stat|status|co|checkout|up|update|ci|commit|info|pg|pget|propget|pl|plist|proplist|relocate|sw|switch)'\\s(.|\\n)*$svnkit-1.7.5+dfsg/svnkit-test/configurations/svn17/cmdline/000077500000000000000000000000001177510526000237035ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/svn17/cmdline/svntest/000077500000000000000000000000001177510526000254115ustar00rootroot00000000000000svnkit-1.7.5+dfsg/svnkit-test/configurations/svn17/cmdline/svntest/main.py000066400000000000000000002016541177510526000267170ustar00rootroot00000000000000# # main.py: a shared, automated test suite for Subversion # # Subversion is a tool for revision control. # See http://subversion.tigris.org for more information. # # ==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. ###################################################################### import sys # for argv[] import os import shutil # for rmtree() import re import stat # for ST_MODE import subprocess import time # for time() import traceback # for print_exc() import threading import optparse # for argument parsing import xml import urllib try: # Python >=3.0 import queue from urllib.parse import quote as urllib_parse_quote from urllib.parse import unquote as urllib_parse_unquote except ImportError: # Python <3.0 import Queue as queue from urllib import quote as urllib_parse_quote from urllib import unquote as urllib_parse_unquote import svntest from svntest import Failure from svntest import Skip ###################################################################### # # HOW TO USE THIS MODULE: # # Write a new python script that # # 1) imports this 'svntest' package # # 2) contains a number of related 'test' routines. (Each test # routine should take no arguments, and return None on success # or throw a Failure exception on failure. Each test should # also contain a short docstring.) # # 3) places all the tests into a list that begins with None. # # 4) calls svntest.main.client_test() on the list. # # Also, your tests will probably want to use some of the common # routines in the 'Utilities' section below. # ##################################################################### # Global stuff default_num_threads = 5 class SVNProcessTerminatedBySignal(Failure): "Exception raised if a spawned process segfaulted, aborted, etc." pass class SVNLineUnequal(Failure): "Exception raised if two lines are unequal" pass class SVNUnmatchedError(Failure): "Exception raised if an expected error is not found" pass class SVNCommitFailure(Failure): "Exception raised if a commit failed" pass class SVNRepositoryCopyFailure(Failure): "Exception raised if unable to copy a repository" pass class SVNRepositoryCreateFailure(Failure): "Exception raised if unable to create a repository" pass # Windows specifics if sys.platform == 'win32': windows = True file_scheme_prefix = 'file:///' _exe = '.exe' _bat = '.bat' os.environ['SVN_DBG_STACKTRACES_TO_STDERR'] = 'y' else: windows = False file_scheme_prefix = 'file://' _exe = '' _bat = '' # The location of our mock svneditor script. if windows: svneditor_script = os.path.join(sys.path[0], 'svneditor.bat') else: svneditor_script = os.path.join(sys.path[0], 'svneditor.py') # Username and password used by the working copies wc_author = 'jrandom' wc_passwd = 'rayjandom' # Username and password used by the working copies for "second user" # scenarios wc_author2 = 'jconstant' # use the same password as wc_author # Set C locale for command line programs os.environ['LC_ALL'] = 'C' # This function mimics the Python 2.3 urllib function of the same name. def pathname2url(path): """Convert the pathname PATH from the local syntax for a path to the form used in the path component of a URL. This does not produce a complete URL. The return value will already be quoted using the quote() function.""" # Don't leave ':' in file://C%3A/ escaped as our canonicalization # rules will replace this with a ':' on input. return urllib_parse_quote(path.replace('\\', '/')).replace('%3A', ':') # This function mimics the Python 2.3 urllib function of the same name. def url2pathname(path): """Convert the path component PATH from an encoded URL to the local syntax for a path. This does not accept a complete URL. This function uses unquote() to decode PATH.""" return os.path.normpath(urllib_parse_unquote(path)) ###################################################################### # The locations of the svn, svnadmin and svnlook binaries, relative to # the only scripts that import this file right now (they live in ../). # Use --bin to override these defaults. svn_binary = os.path.abspath('../../svn/svn' + _exe) svnadmin_binary = os.path.abspath('../../svnadmin/svnadmin' + _exe) svnlook_binary = os.path.abspath('../../svnlook/svnlook' + _exe) svnrdump_binary = os.path.abspath('../../svnrdump/svnrdump' + _exe) svnsync_binary = os.path.abspath('../../svnsync/svnsync' + _exe) svnversion_binary = os.path.abspath('../../svnversion/svnversion' + _exe) svndumpfilter_binary = os.path.abspath('../../svndumpfilter/svndumpfilter' + \ _exe) entriesdump_binary = os.path.abspath('entries-dump' + _exe) atomic_ra_revprop_change_binary = os.path.abspath('atomic-ra-revprop-change' + \ _exe) wc_lock_tester_binary = os.path.abspath('../libsvn_wc/wc-lock-tester' + _exe) wc_incomplete_tester_binary = os.path.abspath('../libsvn_wc/wc-incomplete-tester' + _exe) svnmucc_binary=os.path.abspath('../../../tools/client-side/svnmucc/svnmucc' + \ _exe) # Location to the pristine repository, will be calculated from test_area_url # when we know what the user specified for --url. pristine_greek_repos_url = None # Global variable to track all of our options options = None # End of command-line-set global variables. ###################################################################### # All temporary repositories and working copies are created underneath # this dir, so there's one point at which to mount, e.g., a ramdisk. work_dir = "svn-test-work" # Constant for the merge info property. SVN_PROP_MERGEINFO = "svn:mergeinfo" # Where we want all the repositories and working copies to live. # Each test will have its own! general_repo_dir = os.path.join(work_dir, "repositories") general_wc_dir = os.path.join(work_dir, "working_copies") # temp directory in which we will create our 'pristine' local # repository and other scratch data. This should be removed when we # quit and when we startup. temp_dir = os.path.join(work_dir, 'local_tmp') # (derivatives of the tmp dir.) pristine_greek_repos_dir = os.path.join(temp_dir, "repos") greek_dump_dir = os.path.join(temp_dir, "greekfiles") default_config_dir = os.path.abspath(os.path.join(temp_dir, "config")) # # Our pristine greek-tree state. # # If a test wishes to create an "expected" working-copy tree, it should # call main.greek_state.copy(). That method will return a copy of this # State object which can then be edited. # _item = svntest.wc.StateItem greek_state = svntest.wc.State('', { 'iota' : _item("This is the file 'iota'.\n"), 'A' : _item(), 'A/mu' : _item("This is the file 'mu'.\n"), 'A/B' : _item(), 'A/B/lambda' : _item("This is the file 'lambda'.\n"), 'A/B/E' : _item(), 'A/B/E/alpha' : _item("This is the file 'alpha'.\n"), 'A/B/E/beta' : _item("This is the file 'beta'.\n"), 'A/B/F' : _item(), 'A/C' : _item(), 'A/D' : _item(), 'A/D/gamma' : _item("This is the file 'gamma'.\n"), 'A/D/G' : _item(), 'A/D/G/pi' : _item("This is the file 'pi'.\n"), 'A/D/G/rho' : _item("This is the file 'rho'.\n"), 'A/D/G/tau' : _item("This is the file 'tau'.\n"), 'A/D/H' : _item(), 'A/D/H/chi' : _item("This is the file 'chi'.\n"), 'A/D/H/psi' : _item("This is the file 'psi'.\n"), 'A/D/H/omega' : _item("This is the file 'omega'.\n"), }) ###################################################################### # Utilities shared by the tests def wrap_ex(func): "Wrap a function, catch, print and ignore exceptions" def w(*args, **kwds): try: return func(*args, **kwds) except Failure, ex: if ex.__class__ != Failure or ex.args: ex_args = str(ex) if ex_args: print('EXCEPTION: %s: %s' % (ex.__class__.__name__, ex_args)) else: print('EXCEPTION: %s' % ex.__class__.__name__) return w def setup_development_mode(): "Wraps functions in module actions" l = [ 'run_and_verify_svn', 'run_and_verify_svnversion', 'run_and_verify_load', 'run_and_verify_dump', 'run_and_verify_checkout', 'run_and_verify_export', 'run_and_verify_update', 'run_and_verify_merge', 'run_and_verify_switch', 'run_and_verify_commit', 'run_and_verify_unquiet_status', 'run_and_verify_status', 'run_and_verify_diff_summarize', 'run_and_verify_diff_summarize_xml', 'run_and_validate_lock'] for func in l: setattr(svntest.actions, func, wrap_ex(getattr(svntest.actions, func))) def get_admin_name(): "Return name of SVN administrative subdirectory." if (windows or sys.platform == 'cygwin') \ and 'SVN_ASP_DOT_NET_HACK' in os.environ: return '_svn' else: return '.svn' def wc_is_singledb(wcpath): """Temporary function that checks whether a working copy directory looks like it is part of a single-db working copy.""" pristine = os.path.join(wcpath, get_admin_name(), 'pristine') if not os.path.exists(pristine): return True # Now we must be looking at a multi-db WC dir or the root dir of a # single-DB WC. Sharded 'pristine' dir => single-db, else => multi-db. for name in os.listdir(pristine): if len(name) == 2: return True elif len(name) == 40: return False return False def get_start_commit_hook_path(repo_dir): "Return the path of the start-commit-hook conf file in REPO_DIR." return os.path.join(repo_dir, "hooks", "start-commit") def get_pre_commit_hook_path(repo_dir): "Return the path of the pre-commit-hook conf file in REPO_DIR." return os.path.join(repo_dir, "hooks", "pre-commit") def get_post_commit_hook_path(repo_dir): "Return the path of the post-commit-hook conf file in REPO_DIR." return os.path.join(repo_dir, "hooks", "post-commit") def get_pre_revprop_change_hook_path(repo_dir): "Return the path of the pre-revprop-change hook script in REPO_DIR." return os.path.join(repo_dir, "hooks", "pre-revprop-change") def get_svnserve_conf_file_path(repo_dir): "Return the path of the svnserve.conf file in REPO_DIR." return os.path.join(repo_dir, "conf", "svnserve.conf") def get_fsfs_conf_file_path(repo_dir): "Return the path of the fsfs.conf file in REPO_DIR." return os.path.join(repo_dir, "db", "fsfs.conf") def get_fsfs_format_file_path(repo_dir): "Return the path of the format file in REPO_DIR." return os.path.join(repo_dir, "db", "format") def filter_dbg(lines): for line in lines: if not line.startswith('DBG:'): yield line # Run any binary, logging the command line and return code def run_command(command, error_expected, binary_mode=0, *varargs): """Run COMMAND with VARARGS. Return exit code as int; stdout, stderr as lists of lines (including line terminators). See run_command_stdin() for details. If ERROR_EXPECTED is None, any stderr output will be printed and any stderr output or a non-zero exit code will raise an exception.""" return run_command_stdin(command, error_expected, 0, binary_mode, None, *varargs) # A regular expression that matches arguments that are trivially safe # to pass on a command line without quoting on any supported operating # system: _safe_arg_re = re.compile(r'^[A-Za-z\d\.\_\/\-\:\@]+$') def _quote_arg(arg): """Quote ARG for a command line. Return a quoted version of the string ARG, or just ARG if it contains only universally harmless characters. WARNING: This function cannot handle arbitrary command-line arguments: it is just good enough for what we need here.""" arg = str(arg) if _safe_arg_re.match(arg): return arg if windows: # Note: subprocess.list2cmdline is Windows-specific. return subprocess.list2cmdline([arg]) else: # Quoting suitable for most Unix shells. return "'" + arg.replace("'", "'\\''") + "'" def open_pipe(command, bufsize=0, stdin=None, stdout=None, stderr=None): """Opens a subprocess.Popen pipe to COMMAND using STDIN, STDOUT, and STDERR. BUFSIZE is passed to subprocess.Popen's argument of the same name. Returns (infile, outfile, errfile, waiter); waiter should be passed to wait_on_pipe.""" command = [str(x) for x in command] # On Windows subprocess.Popen() won't accept a Python script as # a valid program to execute, rather it wants the Python executable. if (sys.platform == 'win32') and (command[0].endswith('.py')): command.insert(0, sys.executable) command_string = command[0] + ' ' + ' '.join(map(_quote_arg, command[1:])) if not stdin: stdin = subprocess.PIPE if not stdout: stdout = subprocess.PIPE if not stderr: stderr = subprocess.PIPE p = subprocess.Popen(command, bufsize, stdin=stdin, stdout=stdout, stderr=stderr, close_fds=not windows) return p.stdin, p.stdout, p.stderr, (p, command_string) def wait_on_pipe(waiter, binary_mode, stdin=None): """WAITER is (KID, COMMAND_STRING). Wait for KID (opened with open_pipe) to finish, dying if it does. If KID fails, create an error message containing any stdout and stderr from the kid. Show COMMAND_STRING in diagnostic messages. Normalize Windows line endings of stdout and stderr if not BINARY_MODE. Return KID's exit code as int; stdout, stderr as lists of lines (including line terminators).""" if waiter is None: return kid, command_string = waiter stdout, stderr = kid.communicate(stdin) exit_code = kid.returncode # Normalize Windows line endings if in text mode. if windows and not binary_mode: stdout = stdout.replace('\r\n', '\n') stderr = stderr.replace('\r\n', '\n') # Convert output strings to lists. stdout_lines = stdout.splitlines(True) stderr_lines = stderr.splitlines(True) if exit_code < 0: if not windows: exit_signal = os.WTERMSIG(-exit_code) else: exit_signal = exit_code if stdout_lines is not None: sys.stdout.write("".join(stdout_lines)) sys.stdout.flush() if stderr_lines is not None: sys.stderr.write("".join(stderr_lines)) sys.stderr.flush() if options.verbose: # show the whole path to make it easier to start a debugger sys.stderr.write("CMD: %s terminated by signal %d\n" % (command_string, exit_signal)) sys.stderr.flush() raise SVNProcessTerminatedBySignal else: if exit_code and options.verbose: sys.stderr.write("CMD: %s exited with %d\n" % (command_string, exit_code)) sys.stderr.flush() return stdout_lines, stderr_lines, exit_code def spawn_process(command, bufsize=0, binary_mode=0, stdin_lines=None, *varargs): """Run any binary, supplying input text, logging the command line. BUFSIZE dictates the pipe buffer size used in communication with the subprocess: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered). Normalize Windows line endings of stdout and stderr if not BINARY_MODE. Return exit code as int; stdout, stderr as lists of lines (including line terminators).""" if stdin_lines and not isinstance(stdin_lines, list): raise TypeError("stdin_lines should have list type") # Log the command line if options.verbose and not command.endswith('.py'): sys.stdout.write('CMD: %s %s\n' % (os.path.basename(command), ' '.join([_quote_arg(x) for x in varargs]))) sys.stdout.flush() infile, outfile, errfile, kid = open_pipe([command] + list(varargs), bufsize) if stdin_lines: for x in stdin_lines: infile.write(x) stdout_lines, stderr_lines, exit_code = wait_on_pipe(kid, binary_mode) infile.close() outfile.close() errfile.close() return exit_code, stdout_lines, stderr_lines def run_command_stdin(command, error_expected, bufsize=0, binary_mode=0, stdin_lines=None, *varargs): """Run COMMAND with VARARGS; input STDIN_LINES (a list of strings which should include newline characters) to program via stdin - this should not be very large, as if the program outputs more than the OS is willing to buffer, this will deadlock, with both Python and COMMAND waiting to write to each other for ever. For tests where this is a problem, setting BUFSIZE to a sufficiently large value will prevent the deadlock, see spawn_process(). Normalize Windows line endings of stdout and stderr if not BINARY_MODE. Return exit code as int; stdout, stderr as lists of lines (including line terminators). If ERROR_EXPECTED is None, any stderr output will be printed and any stderr output or a non-zero exit code will raise an exception.""" if options.verbose: start = time.time() exit_code, stdout_lines, stderr_lines = spawn_process(command, bufsize, binary_mode, stdin_lines, *varargs) if options.verbose: stop = time.time() print('