summaryrefslogtreecommitdiff
path: root/src/org/omegat/core/team/SVNRemoteRepository.java
blob: 442ad83c5713b78566a6cf679264bd70d95b421f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/**************************************************************************
 OmegaT - Computer Assisted Translation (CAT) tool 
          with fuzzy matching, translation memory, keyword search, 
          glossaries, and translation leveraging into updated projects.

 Copyright (C) 2012 Alex Buloichik
               2014 Aaron Madlon-Kay
               Home page: http://www.omegat.org/
               Support center: http://groups.yahoo.com/group/OmegaT/

 This file is part of OmegaT.

 OmegaT 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, either version 3 of the License, or
 (at your option) any later version.

 OmegaT 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.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **************************************************************************/
package org.omegat.core.team;

import java.io.File;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import org.omegat.core.Core;
import org.omegat.util.Log;
import org.omegat.util.StringUtil;
import org.tmatesoft.svn.core.SVNAuthenticationException;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNErrorCode;
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.SVNAuthentication;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager;
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.wc.ISVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNStatus;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

/**
 * SVN repository connection implementation.
 * 
 * @author Alex Buloichik (alex73mail@gmail.com)
 * @author Aaron Madlon-Kay
 */
public class SVNRemoteRepository implements IRemoteRepository {
    private static final Logger LOGGER = Logger.getLogger(SVNRemoteRepository.class.getName());

    /** Tests can disable show error. */
    public static boolean SHOW_UNKNOWN_ERRORS = true;

    File baseDirectory;
    SVNClientManager ourClientManager;
    boolean readOnly;

    public static boolean isSVNDirectory(File localDirectory) {
        File svnDir = new File(localDirectory, ".svn");
        return svnDir.exists() && svnDir.isDirectory();
    }

    public boolean isFilesLockingAllowed() {
        return true;
    }

    /**
     * Open working copy.
     */
    public SVNRemoteRepository(File localDirectory) throws Exception {
        this.baseDirectory = localDirectory;
        ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager();
        ourClientManager = SVNClientManager.newInstance(options, authManager);
    }

    public boolean isChanged(File file) throws Exception {
        SVNStatus status = null;
        try {
            status = ourClientManager.getStatusClient().doStatus(file, false);
        } catch (SVNException e) {
            if (e.getErrorMessage().getErrorCode().getCode()==155007) {
                //file is outside repository, so not under version control.
                return false;
            } else throw e;
        }
        //if file does not exist and not under version control, then return false.
        if (status == null) return false;
        SVNStatusType statusType = status.getContentsStatus();
        //hmm, if file not under version control, status is STATUS_NONE, and not STATUS_UNVERSIONED?
        return statusType != SVNStatusType.STATUS_NORMAL && statusType != SVNStatusType.STATUS_UNVERSIONED && statusType != SVNStatusType.STATUS_NONE;
    }

    public boolean isUnderVersionControl(File file) throws Exception {
        SVNStatus status = null;
        try {
            status = ourClientManager.getStatusClient().doStatus(file, false);
        } catch (SVNException e) {
            if (e.getErrorMessage().getErrorCode().getCode()==155007) {
                //file is outside repository, so not under version control.
                return false;
            } else throw e;
        }
        //if file does not exist and not under version control, then return false.
        if (status == null) return false;
        SVNStatusType statusType = status.getContentsStatus();
        //hmm, if file not under version control, status is STATUS_NONE, and not STATUS_UNVERSIONED?
        return statusType != SVNStatusType.STATUS_UNVERSIONED && statusType != SVNStatusType.STATUS_NONE;
    }

    public void setCredentials(Credentials credentials) {
        if (credentials == null) {
            return;
        }
        ourClientManager.dispose();

        DefaultSVNAuthenticationManager authManager = new DefaultSVNAuthenticationManager(null, true,
                credentials.username, new String(credentials.password));
        if (credentials.saveAsPlainText) {
            authManager.setAuthenticationStorageOptions(FORCE_SAVE_PLAIN_PASSWORD);
        }
        ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        ourClientManager = SVNClientManager.newInstance(options, authManager);
        setReadOnly(credentials.readOnly);
    }

    public void setReadOnly(boolean value) {
        readOnly = value;
    }

    public void updateFullProject() throws SocketException, Exception {
        Log.logInfoRB("SVN_START", "update");
        try {
            long rev = ourClientManager.getUpdateClient().doUpdate(baseDirectory, SVNRevision.HEAD, SVNDepth.INFINITY,
                    false, false);
            Log.logDebug(LOGGER, "SVN updated to revision {0}", rev);
            Log.logInfoRB("SVN_FINISH", "update");
        } catch (SVNAuthenticationException ex) {
            // authentication failed - need to ask username/password
            Log.logWarningRB("SVN_ERROR", "update", ex.getMessage());
            throw new AuthenticationException(ex);
        } catch (SVNException ex) {
            Log.logErrorRB("SVN_ERROR", "update", ex.getMessage());
            checkNetworkException(ex);
            throw ex;
        } catch (Exception ex) {
            Log.logErrorRB("SVN_ERROR", "update", ex.getMessage());
            throw ex;
        }
    }

    public void checkoutFullProject(String repositoryURL) throws Exception {
        Log.logInfoRB("SVN_START", "checkout");

        SVNURL url = SVNURL.parseURIDecoded(repositoryURL);
        try {
            long rev = ourClientManager.getUpdateClient().doCheckout(url, baseDirectory, SVNRevision.HEAD,
                    SVNRevision.HEAD, SVNDepth.INFINITY, false);
            Log.logDebug(LOGGER, "SVN checked out to revision {0}", rev);
            Log.logInfoRB("SVN_FINISH", "checkout");
        } catch (SVNAuthenticationException ex) {
            // authentication failed - need to ask username/password
            Log.logWarningRB("TEAM_WRONG_AUTHENTICATION");
            throw new AuthenticationException(ex);
        } catch (Exception ex) {
            Log.logErrorRB("SVN_ERROR", "checkout", ex.getMessage());
            throw ex;
        }
    }

    public String getBaseRevisionId(File file) throws Exception {
        SVNInfo info = ourClientManager.getWCClient().doInfo(file, SVNRevision.BASE);
        Log.logDebug(LOGGER, "SVN committed revision for file {0} is {1}", file, info.getCommittedRevision().getNumber());

        return Long.toString(info.getCommittedRevision().getNumber());
    }

    public void restoreBase(File[] files) throws Exception {
        ourClientManager.getWCClient().doRevert(files, SVNDepth.EMPTY, null);
        Log.logDebug(LOGGER, "SVN restore base for {0}", toList(files));
    }

    public void download(File[] files) throws SocketException, Exception {
        Log.logInfoRB("SVN_START", "download");
        try {
            long[] revs = ourClientManager.getUpdateClient().doUpdate(files, SVNRevision.HEAD, SVNDepth.INFINITY,
                    false, false);
            Log.logDebug(LOGGER, "SVN updated files {0} to revisions {1}", toList(files), toList(revs));
            Log.logInfoRB("SVN_FINISH", "download");
        } catch (SVNException ex) {
            Log.logErrorRB("SVN_ERROR", "download", ex.getMessage());
            checkNetworkException(ex);
            throw ex;
        } catch (Exception ex) {
            Log.logErrorRB("SVN_ERROR", "download", ex.getMessage());
            throw ex;
        }
    }

    public void reset() throws Exception {
        Log.logInfoRB("SVN_START", "reset");
        try {
            // not tested. Can anyone confirm this code?
            Log.logDebug(LOGGER, "SVN revert all files in {0}", baseDirectory);
            ourClientManager.getWCClient().doRevert(new File[] { baseDirectory }, SVNDepth.INFINITY,
                    (Collection<String>) null);
            Log.logInfoRB("SVN_FINISH", "reset");
        } catch (Exception ex) {
            Log.logErrorRB("SVN_ERROR", "reset", ex.getMessage());
            throw ex;
        }
    }

    public void upload(File file, String commitMessage) throws SocketException, Exception {
        if (readOnly) {
            // read-only - upload disabled
            Log.logInfoRB("SVN_READONLY");
            return;
        }

        Log.logInfoRB("SVN_START", "upload");
        try {
            SVNCommitInfo info = ourClientManager.getCommitClient().doCommit(new File[] { file }, false, commitMessage,
                    null, null, false, false, SVNDepth.INFINITY);
            Log.logDebug(LOGGER, "SVN committed file {0} into new revision {1}", file, info.getNewRevision());
            Log.logInfoRB("SVN_FINISH", "upload");
        } catch (SVNAuthenticationException ex) {
            // authentication failed - need to ask username/password
            Log.logWarningRB("SVN_ERROR", "update", ex.getMessage());
            throw new AuthenticationException(ex);
        } catch (SVNException ex) {
            if (Arrays.asList(SVNErrorCode.FS_TXN_OUT_OF_DATE, SVNErrorCode.WC_NOT_UP_TO_DATE, SVNErrorCode.FS_CONFLICT)
                    .contains(ex.getErrorMessage().getErrorCode())) {
                // Somebody else committed changes - it's normal. Will upload on next save.
                Log.logWarningRB("SVN_CONFLICT");
                return;
            } else {
                Log.logErrorRB("SVN_ERROR", "upload", ex.getMessage());
                checkNetworkException(ex);
            }
            if (SHOW_UNKNOWN_ERRORS) {
                Core.getMainWindow().showErrorDialogRB("SVN_UPLOAD_ERROR_TITLE", "SVN_UPLOAD_ERROR",
                        ex.getMessage());
            }
            throw ex;
        } catch (Exception ex) {
            Log.logErrorRB("SVN_ERROR", "upload", ex.getMessage());
            throw ex;
        }
    }

    List<File> toList(File[] files) {
        return Arrays.asList(files);
    }

    List<Long> toList(long[] arr) {
        List<Long> result = new ArrayList<Long>(arr.length);
        for (long v : arr) {
            result.add(v);
        }
        return result;
    }

    void checkNetworkException(Exception ex) throws NetworkException {
        if (ex.getCause() instanceof SocketException) {
            throw new NetworkException(ex.getCause());
        }
        if (ex instanceof SVNException) {
            SVNException se = (SVNException) ex;
            if (se.getErrorMessage().getErrorCode().getCategory() == SVNErrorCode.RA_DAV_CATEGORY) {
                throw new NetworkException(se);
            }
        }
    }

    static ISVNAuthenticationStorageOptions FORCE_SAVE_PLAIN_PASSWORD = new ISVNAuthenticationStorageOptions() {
        public boolean isNonInteractive() throws SVNException {
            return false;
        }

        public ISVNAuthStoreHandler getAuthStoreHandler() throws SVNException {
            return FORCE_SAVE_PLAIN_PASSWORD_HANDLER;
        }

        public boolean isSSLPassphrasePromptSupported() {
            return false;
        }

        public ISVNGnomeKeyringPasswordProvider getGnomeKeyringPasswordProvider() {
            return null;
        }
    };

    static ISVNAuthStoreHandler FORCE_SAVE_PLAIN_PASSWORD_HANDLER = new ISVNAuthStoreHandler() {
        public boolean canStorePlainTextPassphrases(String realm, SVNAuthentication auth) throws SVNException {
            return false;
        }

        public boolean canStorePlainTextPasswords(String realm, SVNAuthentication auth) throws SVNException {
            return true;
        }
    };
    
    /**
     * Determines whether or not the supplied URL represents a valid Subversion repository.
     * 
     * <p>Does the equivalent of <code>svn info <i>url</i></code>.
     * 
     * @param url URL of supposed remote repository
     * @return true if repository appears to be valid, false otherwise
     */
    public static boolean isSVNRepository(String url, Credentials credentials)
            throws AuthenticationException {
        // Heuristics to save some waiting time
        if (url.startsWith("git://")) {
            return false;
        }
        try {
            SVNURL svnurl = SVNURL.parseURIDecoded(url);
            SVNClientManager manager = SVNClientManager.newInstance();
            ISVNAuthenticationManager authManager;
            if (credentials != null) {
                DefaultSVNAuthenticationManager defaultManager = new DefaultSVNAuthenticationManager(null,
                        true, credentials.username, new String(credentials.password));
                if (credentials.saveAsPlainText) {
                    defaultManager.setAuthenticationStorageOptions(FORCE_SAVE_PLAIN_PASSWORD);
                }
                authManager = defaultManager;
            } else {
                authManager = SVNWCUtil.createDefaultAuthenticationManager();
            }
            manager.setAuthenticationManager(authManager);
            manager.getWCClient().doInfo(svnurl, SVNRevision.HEAD, SVNRevision.HEAD);
        } catch (SVNAuthenticationException ex) {
            throw new AuthenticationException(ex);
        } catch (SVNException ex) {
            return false;
        }
        return true;
    }

    public static String guessRepoName(String url) {
        url = StringUtil.stripFromEnd(url, "/", "/trunk", "/branches", "/tags", "/svn");
        return url.substring(url.lastIndexOf('/') + 1);
    }
}