netbeans-cvsclient_6.5/ 0000755 0001753 0000144 00000000000 11175434272 014130 5 ustar ludo users netbeans-cvsclient_6.5/build.xml 0000644 0001753 0000144 00000004170 11175406776 015763 0 ustar ludo users
CVSRoot represents the cvsroot that identifies the cvs repository's location and the means to get to it. We use following definition of cvsroot:
[:method:][[user][:password]@][hostname[:[port]]]/path/to/repository
When the method is not defined, we treat it as local or ext method depending on whether the hostname is present or not. This gives us two different formats:
[:method:]/path/to/repository
or
(:local:|:fork:)anything
2. Server format
[:method:][[user][:password]@]hostname[:[port]]/path/to/repository
There are currently 6 different methods that are implemented by 3 different connection classes.
- :local:, :fork: & no-method --> LocalConnection (LOCAL_FORMAT)
- :server: & :ext: --> SSH2Connection (SERVER_FORMAT)
- :pserver: --> PServerConnection (SERVER_FORMAT)
gserver and kserver are not included. Environment variables are not used (like CVS_RSH).
local and no-method work like fork. They start the cvs server program on
the local machine thus using the remote protocol on the local machine.
According to Cederqvist fork's relation to local is:
"In other words it does pretty much the same thing as :local:,
but various quirks, bugs and the like are those of the remote CVS rather
than the local CVS."
server is using ssh. According to Cederqvist it would use an internal RSH
client but since it is not known what this exactly means it just uses ssh.
Note ssh is able only to use ssh protocol version 2 which is recommended anyways.
Note that cvsroot is case sensitive so remember to write the method in lowercase.
You can succesfully construct a cvsroot that has a different method but
ConnectionFactory will be unable to create a connection for such CVSRoot.
CVSRoot object keeps the cvsroot in components that are
- method
- user
- password
- host
- port
- repository
You can change these components through setters.
When you ask fo the cvsroot string representation it is constructed based
on the current values of the components. The returned cvsroot never contains
the password for security reasons.
Also "no-method" is always represented as local method.
*/
public class CVSRoot {
/** A constant representing the "local" connection method. */
public static final String METHOD_LOCAL = "local"; // NOI18N
/** A constant representing the "fork" connection method. */
public static final String METHOD_FORK = "fork"; // NOI18N
/** A constant representing the "server" connection method. */
public static final String METHOD_SERVER = "server"; // NOI18N
/** A constant representing the "pserver" connection method. */
public static final String METHOD_PSERVER = "pserver"; // NOI18N
/** A constant representing the "ext" connection method. */
public static final String METHOD_EXT = "ext"; // NOI18N
// the connection method. no-method is represented by null
// the value is interned for fast comparisons
private String method;
// user (default = null)
private String username;
// password (default = null)
private String password;
// hostname (default = null)
private String hostname;
// port (default = 0) 0 means that port is not used and the protocol will use default protocol
private int port;
// repository as string representation
private String repository;
/**
* Parse the CVSROOT string into CVSRoot object.
* The CVSROOT string must be of the form
* [:method:][[user][:password]@][hostname:[port]]/path/to/repository
*/
public static CVSRoot parse(String cvsroot) throws IllegalArgumentException {
return new CVSRoot(cvsroot);
}
/**
* Construct CVSRoot from Properties object.
* The names are exactly the same as the attribute names in this class.
*/
public static CVSRoot parse(Properties props) throws IllegalArgumentException {
return new CVSRoot(props);
}
/**
* This constructor allows to construct CVSRoot from Properties object.
* The names are exactly the same as the attribute names in this class.
*/
protected CVSRoot(Properties props) throws IllegalArgumentException {
String mtd = props.getProperty("method");
if (mtd != null) {
this.method = mtd.intern();
}
// host & port
this.hostname = props.getProperty("hostname");
if (this.hostname.length() == 0)
this.hostname = null;
//this.localFormat = this.hostname == null || this.hostname.length() == 0;
if (this.hostname != null) {
// user & password (they are always optional)
this.username = props.getProperty("username");
this.password = props.getProperty("password");
// host & port
// We already have hostname
try {
int p = Integer.parseInt(props.getProperty("port"));
if (p > 0)
this.port = p;
else
throw new IllegalArgumentException("The port is not a positive number.");
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("The port is not a number: '"+props.getProperty("port")+"'.");
}
}
// and the most important which is repository
String r = props.getProperty("repository");
if (r == null)
throw new IllegalArgumentException("Repository is obligatory.");
else
this.repository = r;
}
/**
* Breaks the string representation of cvsroot into it's components:
*
* The valid format (from the cederqvist) is:
*
* :method:[[user][:password]@]hostname[:[port]]/path/to/repository
*
* Also parse alternative format from WinCVS, which stores connection
* parameters such as username and hostname in method options:
*
* :method[;option=arg...]:other_connection_data
*
* e.g. :pserver;username=anonymous;hostname=localhost:/path/to/repository
*
* For CVSNT compatability it also supports following local repository path format
*
* driveletter:path\\path\\path
*
*/
protected CVSRoot(String cvsroot) throws IllegalArgumentException {
int colonPosition = 0;
boolean localFormat;
if (cvsroot.startsWith(":") == false) {
// no method mentioned guess it using heuristics
localFormat = cvsroot.startsWith("/");
if (localFormat == false) {
if (cvsroot.indexOf(':') == 1 && cvsroot.indexOf('\\') == 2) {
//#67504 it looks like windows drive => local
method = METHOD_LOCAL;
repository = cvsroot;
return;
}
colonPosition = cvsroot.indexOf(':');
if (colonPosition < 0) {
// No colon => server format, but there must be a '/' in the middle
int slash = cvsroot.indexOf('/');
if (slash < 0) {
throw new IllegalArgumentException("CVSROOT must be an absolute pathname.");
}
method = METHOD_SERVER;
} else {
method = METHOD_EXT;
}
colonPosition = 0;
} else {
method = METHOD_LOCAL;
}
} else {
// connection method is given so parse it
colonPosition = cvsroot.indexOf(':', 1);
if (colonPosition < 0)
throw new IllegalArgumentException("The connection method does not end with ':'.");
int methodNameEnd = colonPosition;
int semicolonPosition = cvsroot.indexOf(";", 1);
if (semicolonPosition != -1 && semicolonPosition < colonPosition) {
// method has options
methodNameEnd = semicolonPosition;
String options = cvsroot.substring(semicolonPosition +1, colonPosition);
StringTokenizer tokenizer = new StringTokenizer(options, "=;");
while (tokenizer.hasMoreTokens()) {
String option = tokenizer.nextToken();
if (tokenizer.hasMoreTokens() == false) {
throw new IllegalArgumentException("Undefined " + option + " option value.");
}
String value = tokenizer.nextToken();
if ("hostname".equals(option)) { // NOI18N
hostname = value;
} else if ("username".equals(option)) { // NOI18N
username = value;
} else if ("password".equals(option)) { // NOI18N
password = value;
} if ("port".equals(option)) { // NOI18N
try {
port = Integer.parseInt(value, 10);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Port option must be number.");
}
}
}
}
this.method = cvsroot.substring(1, methodNameEnd).intern();
//#65742 read E!e>2.0 workdirs
if ("extssh".equals(method)) { // NOI18N
method = METHOD_EXT;
}
// CVSNT supports :ssh;ver=2:username@cvs.sf.net:/cvsroot/xoops
if ("ssh".equals(method)) { // NOI18N
method = METHOD_EXT;
}
colonPosition++;
// Set local format in case of :local: or :fork: methods.
localFormat = isLocalMethod(this.method);
}
if (localFormat) {
// everything after method is repository in local format
this.repository = cvsroot.substring(colonPosition);
} else {
/* So now we parse SERVER_FORMAT
:method:[[user][:password]@]hostname[:[port]]/reposi/tory
ALGORITHM:
- find the first '@' character
- not found:
- find the first ':'
- not found
- find the first '/'
- not found
- exception
- found
- parse hostname/path/to/repository
- found
- parse rest
- found
- find the following ':' character
- not found
- exception
- found
parse rest
*/
int startSearch = cvsroot.substring(colonPosition).lastIndexOf('@');
if (startSearch != -1) startSearch += colonPosition;
if (startSearch < 0) startSearch = colonPosition;
String userPasswdHost;
int pathBegin = -1;
int hostColon = cvsroot.indexOf(':', startSearch);
if (hostColon == -1) {
pathBegin = cvsroot.indexOf('/', startSearch);
if (pathBegin < 0) {
throw new IllegalArgumentException("cvsroot " + cvsroot + " is malformed, host name is missing.");
} else {
userPasswdHost = cvsroot.substring(colonPosition, pathBegin);
}
} else {
userPasswdHost = cvsroot.substring(colonPosition, hostColon);
}
int at = userPasswdHost.lastIndexOf('@');
if (at == -1) {
// there is no user or password, only hostname before port
if (userPasswdHost.length() > 0) {
this.hostname = userPasswdHost;
}
}
else {
// there is user, password or both before hostname
// up = username, password or both
String up = userPasswdHost.substring(0, at);
if (up.length() > 0) {
int upDivider = up.indexOf(':');
if (upDivider != -1) {
this.username = up.substring(0, upDivider);
this.password = up.substring(upDivider+1);
}
else {
this.username = up;
}
}
// hostname
this.hostname = userPasswdHost.substring(at+1);
}
if (hostname == null || hostname.length() == 0) {
throw new IllegalArgumentException("Didn't specify hostname in CVSROOT '"+cvsroot+"'.");
}
/*
Now we are left with port (optional) and repository after hostColon
pr = possible port and repository
*/
if (hostColon > 0) {
String pr = cvsroot.substring(hostColon+1);
int index = 0;
int port = 0;
char c;
while (pr.length() > index && Character.isDigit(c = pr.charAt(index))) {
int d = Character.digit(c, 10);
port = port*10 + d;
index++;
}
this.port = port;
if (index > 0) pr = pr.substring(index);
if (pr.startsWith(":")) { // NOI18N
pr = pr.substring(1);
}
this.repository = pr;
} else {
this.port = 0;
this.repository = cvsroot.substring(pathBegin);
}
}
}
/**
* Test whether this cvsroot describes a local connection or remote connection.
* The connection is local if and only if the host name is null
.
* E.g. for local or fork methods.
*/
public boolean isLocal() {
return hostname == null;
}
/**
-
LOCAL_FORMAT --> :method:/reposi/tory
"no method" is always represented internally as null
-
SERVER_FORMAT --> :method:user@hostname:[port]/reposi/tory
Password is never included in cvsroot string representation. Use getPassword to get it.
*/
public String toString() {
if (this.hostname == null) {
if (this.method == null)
return this.repository;
return ":" + this.method + ":" + this.repository;
} else {
StringBuffer buf = new StringBuffer();
if (this.method != null) {
buf.append(':');
buf.append(this.method);
buf.append(':');
}
// don't put password in cvsroot
if (this.username != null) {
buf.append(this.username);
buf.append('@');
}
// hostname
buf.append(this.hostname);
buf.append(':');
// port
if (this.port > 0)
buf.append(this.port);
// repository
buf.append(this.repository);
return buf.toString();
}
}
/**
With this method it is possible to compare how close two CVSRoots are to each other. The possible values are:
- -1 = not compatible - if none of the below match
- 0 = when equals(..) returns true
- 1 = refers to same repository on the same machine using same method on same port and same user
- 2 = refers to same repository on the same machine using same method
- 3 = refers to same repository on the same machine
*/
public int getCompatibilityLevel(CVSRoot compared) {
if (equals(compared))
return 0;
boolean sameRepository = isSameRepository(compared);
boolean sameHost = isSameHost(compared);
boolean sameMethod = isSameMethod(compared);
boolean samePort = isSamePort(compared);
boolean sameUser = isSameUser(compared);
if (sameRepository && sameHost && sameMethod && samePort && sameUser)
return 1;
else if (sameRepository && sameHost && sameMethod)
return 2;
else if (sameRepository && sameHost)
return 3;
else
return -1;
}
private boolean isSameRepository(CVSRoot compared) {
if (this.repository.equals(compared.repository)) {
return true;
}
try {
if (
(new File(this.repository)).getCanonicalFile().equals(
new File(compared.repository).getCanonicalFile()
)
)
return true;
else
return false;
}
catch (IOException ioe) {
// something went wrong when invoking getCanonicalFile() so return false
return false;
}
}
private boolean isSameHost(CVSRoot compared) {
String comparedHostName = compared.getHostName();
if (this.hostname == comparedHostName) {
return true;
}
if (this.hostname != null) {
return this.hostname.equalsIgnoreCase(comparedHostName);
} else {
return false;
}
}
private boolean isSameMethod(CVSRoot compared) {
if (this.method == null)
if (compared.getMethod() == null)
return true;
else
return false;
else if (this.method.equals(compared.getMethod()))
return true;
else
return false;
}
private boolean isSamePort(CVSRoot compared) {
if (this.isLocal() == compared.isLocal())
if (this.isLocal())
return true;
else if (this.port == compared.getPort())
return true;
else {
try {
Connection c1 = ConnectionFactory.getConnection(this);
Connection c2 = ConnectionFactory.getConnection(compared);
// Test actual ports used by the connections.
// This is necessary in case that port in CVSRoot is zero and the conection is using some default port number.
return c1.getPort() == c2.getPort();
} catch (IllegalArgumentException iaex) {
return false;
}
}
else
return false;
}
private boolean isSameUser(CVSRoot compared) {
String user = compared.getUserName();
if (user == getUserName()) return true;
if (user != null) {
return user.equals(getUserName());
}
return false;
}
/**
* CVSRoots are equal if their toString representations are equal.
* This puts some extra pressure on the toString method that should be defined very precisely.
*/
public boolean equals(Object o) {
// This should be null safe, right?
if (!(o instanceof CVSRoot))
return false;
CVSRoot compared = (CVSRoot) o;
if (toString().equals(compared.toString()))
return true;
return false;
}
public int hashCode() {
return toString().hashCode();
}
/**
* Get the format of this cvsroot.
* @return Either {@link #LOCAL_FORMAT} or {@link #SERVER_FORMAT}.
*
public int getUrlFormat() {
return urlFormat;
}
*/
/**
* Get the connection method.
* @return The connection method or null
when no method is defined.
*/
public String getMethod() {
return method;
}
/**
setting the method has effects on other components.
The method might change
- urlFormat
- username and password
- hostname/port
If urlFormat becomes LOCAL_FORMAT then username, password and hostname are set to null and port to 0.
If urlFormat becomes SERVER_FORMAT then hostname must not be null.
*/
protected void setMethod(String method) {
if (method != null) {
this.method = method.intern();
} else {
method = null;
}
if (isLocalMethod(method)) {
this.username = null;
this.password = null;
this.hostname = null;
this.port = 0;
}
else {
if (this.hostname == null)
throw new IllegalArgumentException("Hostname must not be null when setting a remote method.");
}
}
// test whether the method is "local" or "fork"
private boolean isLocalMethod(String method) {
return METHOD_LOCAL == method || METHOD_FORK == method;
}
/**
* Get the user name.
* @return The user name or code>null
when the user name is not defined.
*/
public String getUserName() {
return username;
}
/**
* Set the user name.
* @param username The user name.
*/
protected void setUserName(String username) {
this.username = username;
}
/**
* Get the password.
* @return The password or null
when the password is not defined.
*/
public String getPassword() {
return this.password;
}
/**
* Set the password.
* @param password The password
*/
protected void setPassword(String password) {
this.password = password;
}
/**
* Get the host name.
* @return The host name or null
when the host name is
* not defined
*/
public String getHostName() {
return this.hostname;
}
/**
* Set the host name.
* @param hostname The host name or null
when the host name is
* not defined.
*/
protected void setHostName(String hostname) {
this.hostname = hostname;
}
/**
* Get the port number.
* @return The port number or zero when the port is not defined.
*/
public int getPort() {
return this.port;
}
/**
* Set the port number.
* @param port The port number or zero when the port is not defined.
*/
public void setPort(int port) {
this.port = port;
}
/**
* Get the repository.
* @return The repository. This is never null
.
*/
public String getRepository() {
return repository;
}
/**
* Set the repository.
* @param repository The repository. Must not be null
.
*/
protected void setRepository(String repository) {
if (repository == null) {
throw new IllegalArgumentException("The repository must not be null.");
}
this.repository = repository;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/Client.java 0000644 0001753 0000144 00000113366 11175406776 024150 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.file.*;
import org.netbeans.lib.cvsclient.request.*;
import org.netbeans.lib.cvsclient.response.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* The main way of communication with a server using the CVS Protocol. The
* client is not responsible for setting up the connection with the server,
* only interacting with it.
* @see org.netbeans.lib.cvsclient.connection.Connection
* @author Robert Greig
*/
public class Client implements ClientServices, ResponseServices {
/**
* The connection used to interact with the server.
*/
private Connection connection;
/**
* The file handler to use.
*/
private FileHandler transmitFileHandler;
private FileHandler gzipFileHandler = new GzippedFileHandler();
private FileHandler uncompFileHandler = new DefaultFileHandler();
private boolean dontUseGzipFileHandler;
/**
* The modified date.
*/
private Date modifiedDate;
/**
* The admin handler to use.
*/
private AdminHandler adminHandler;
/**
* The local path, ie the path to the directory in which this command
* was executed.
*/
private String localPath;
/**
* Whether any commands have been executed so far. This allows us to
* send some initialisation requests before the first command.
*/
private boolean isFirstCommand = true;
/**
* The event manager.
*/
private final EventManager eventManager = new EventManager(this);
/**
* The global options for the executing command.
*/
private GlobalOptions globalOptions;
private PrintStream stderr = System.err;
/**
* This is set to true if we should abort the current command.
*/
private boolean abort;
private ResponseFactory responseFactory;
private IgnoreFileFilter ignoreFileFilter;
/*
* The valid list of requests that is valid for the CVS server
* corresponding to this client
*/
private Map validRequests = new HashMap();
/**
* A map of file patterns and keyword substitution options
*/
private Map wrappersMap = null;
/**
* This will be set to true after initialization requests are sent
* to the server. The initialization requests setup valid requests
* and send RootRequest to the server.
*/
private boolean initialRequestsSent = false;
private boolean printConnectionReuseWarning = false;
private static final Set ALLOWED_CONNECTION_REUSE_REQUESTS =
new HashSet(Arrays.asList(new Class[] { ExpandModulesRequest.class, WrapperSendRequest.class }));
// processRequests & getCounter
private LoggedDataInputStream loggedDataInputStream;
private LoggedDataOutputStream loggedDataOutputStream;
private boolean warned;
/**
* Construct a Client using a given connection and file handler.
* You must initialize the connection and adminHandler first.
*
* // establish connection to the given CVS pserver
* PServerConnection connection = new PServerConnection();
* connection.setUserName(userName);
* connection.setHostName(hostName);
* connection.setEncodedPassword(StandardScrambler.getInstance().scramble(password));
* connection.setRepository(repository);
* // test the connection
* try {
* connection.open();
* } catch (AuthenticationException e) {
* // do something
* }
*
* // create a CVS client
* Client cvsClient = new Client(connection,new StandardAdminHandler());
*
* // set the directory in which we work
* cvsClient.setLocalPath(localPath);
*
* @param connection the connection to the cvs server
* @param adminHandler the admin handler to use
*/
public Client(Connection connection, AdminHandler adminHandler) {
setConnection(connection);
setAdminHandler(adminHandler);
ignoreFileFilter = new DefaultIgnoreFileFilter();
dontUseGzipFileHandler = false;
}
public void setErrorStream(PrintStream stderr) {
this.stderr = stderr;
}
/**
* Get the connection used for communicating with the server.
* Connection.
* @return the connection
*/
public Connection getConnection() {
return connection;
}
/**
* Set the connection used for communicating with the server.
* @param c the connection to use for all communication with the server
*/
public void setConnection(Connection connection) {
this.connection = connection;
initialRequestsSent = false;
setIsFirstCommand(true);
}
/**
* Get the admin handler uesd to read and write administrative information
* about files on the local machine.
* @return the admin handler
*/
public AdminHandler getAdminHandler() {
return adminHandler;
}
/**
* Set the admin handler used to read and write administrative information
* about files on the local machine.
*/
public void setAdminHandler(AdminHandler adminHandler) {
this.adminHandler = adminHandler;
}
/**
* Get the local path; that is, the path to the directory in which
* the currently executing command is referring.
*/
public String getLocalPath() {
return localPath;
}
/**
* Set the local path, i.e. the path to the directory in which all
* commands are given (top level).
*/
public void setLocalPath(String localPath) {
// remove trailing (back-) slash
localPath = localPath.replace('\\', '/');
while (localPath.endsWith("/")) { // NOI18N
localPath = localPath.substring(0, localPath.length() - 1);
}
this.localPath = localPath;
}
/**
* Returns true if no previous command was executed using thiz.
*/
public boolean isFirstCommand() {
return isFirstCommand;
}
/**
* Set whether this is the first command. Normally you do not need to set
* this yourself - after execution the first command will have set this to
* false.
*/
public void setIsFirstCommand(boolean isFirstCommand) {
this.isFirstCommand = isFirstCommand;
}
/**
* Return the uncompressed file handler.
*/
public FileHandler getUncompressedFileHandler() {
return uncompFileHandler;
}
/**
* Set the uncompressed file handler.
*/
public void setUncompressedFileHandler(FileHandler uncompFileHandler) {
this.uncompFileHandler = uncompFileHandler;
}
/**
* Return the Gzip stream handler.
*/
public FileHandler getGzipFileHandler() {
return gzipFileHandler;
}
/**
* Set the handler for Gzip data.
*/
public void setGzipFileHandler(FileHandler gzipFileHandler) {
this.gzipFileHandler = gzipFileHandler;
}
/**
* ReSet the filehandler for Gzip compressed data. Makes sure the
* requests for sending gzipped data are not sent..
*/
public void dontUseGzipFileHandler() {
setGzipFileHandler(new DefaultFileHandler());
dontUseGzipFileHandler = true;
}
public boolean isAborted() {
return abort;
}
/**
* Ensures, that the connection is open.
*
* @throws AuthenticationException if it wasn't possible to connect
*/
public void ensureConnection() throws AuthenticationException {
BugLog.getInstance().assertNotNull(getConnection());
if (getConnection().isOpen()) {
return;
}
// #69689 detect silent servers, possibly caused by proxy errors
final Throwable ex[] = new Throwable[1];
final boolean opened[] = new boolean[] {false};
Runnable probe = new Runnable() {
public void run() {
try {
getConnection().open();
synchronized(opened) {
opened[0] = true;
}
} catch (Throwable e) {
synchronized(ex) {
ex[0] = e;
}
}
}
};
Thread probeThread = new Thread(probe, "CVS Server Probe"); // NOI18N
probeThread.start();
try {
probeThread.join(60 * 1000); // 1 min
Throwable wasEx;
synchronized(ex) {
wasEx = ex[0];
}
if (wasEx != null) {
if (wasEx instanceof CommandAbortedException) {
// User cancelled
abort();
return;
} else if (wasEx instanceof AuthenticationException) {
throw (AuthenticationException) wasEx;
} else if (wasEx instanceof RuntimeException) {
throw (RuntimeException) wasEx;
} else if (wasEx instanceof Error) {
throw (Error) wasEx;
} else {
assert false : wasEx;
}
}
boolean wasOpened;
synchronized(opened) {
wasOpened = opened[0];
}
if (wasOpened == false) {
probeThread.interrupt();
throw new AuthenticationException("Timeout, no response from server.", "Timeout, no response from server.");
}
} catch (InterruptedException e) {
// User cancelled
probeThread.interrupt();
abort();
}
}
/**
* Process all the requests. The connection must have been opened and
* set first.
* @param requests the requets to process
*/
public void processRequests(List requests)
throws IOException, UnconfiguredRequestException, ResponseException,
CommandAbortedException {
if (requests == null || requests.size() == 0) {
throw new IllegalArgumentException("[processRequests] requests " + // NOI18N
"was either null or empty."); // NOI18N
}
if (abort) {
throw new CommandAbortedException("Aborted during request processing", // NOI18N
CommandException.getLocalMessage("Client.commandAborted", null)); //NOI18N
}
loggedDataInputStream = null;
loggedDataOutputStream = null;
// send the initialisation requests if we are handling the first
// command
boolean filterRootRequest = true;
if (isFirstCommand()) {
setIsFirstCommand(false);
int pos = 0;
if (!initialRequestsSent) {
pos = fillInitialRequests(requests);
initialRequestsSent = true;
filterRootRequest = false;
}
if (globalOptions != null) {
// sends the global options that are to be sent to server (-q, -Q, -t, -n, l)
for (Iterator it = globalOptions.createRequestList().iterator(); it.hasNext();) {
Request request = (Request)it.next();
requests.add(pos++, request);
}
if (globalOptions.isUseGzip() && globalOptions.getCompressionLevel() != 0) {
requests.add(pos++, new GzipFileContentsRequest(globalOptions.getCompressionLevel()));
}
}
} else if (printConnectionReuseWarning) {
if (System.getProperty("javacvs.multiple_commands_warning") == null) { //NOI18N
System.err.println("WARNING TO DEVELOPERS:"); //NOI18N
System.err.println("Please be warned that attempting to reuse one open connection for more commands is not supported by cvs servers very well."); //NOI18N
System.err.println("You are advised to open a new Connection each time."); //NOI18N
System.err.println("If you still want to proceed, please do: System.setProperty(\"javacvs.multiple_commands_warning\", \"false\")"); //NOI18N
System.err.println("That will disable this message."); //NOI18N
}
}
if (!ALLOWED_CONNECTION_REUSE_REQUESTS.contains(requests.get(requests.size() - 1).getClass())) {
printConnectionReuseWarning = true;
}
final boolean fireEnhancedEvents = getEventManager().isFireEnhancedEventSet();
int fileDetailRequestCount = 0;
if (fireEnhancedEvents) {
for (Iterator it = requests.iterator(); it.hasNext();) {
Request request = (Request)it.next();
FileDetails fileDetails = request.getFileForTransmission();
if (fileDetails != null && fileDetails.getFile().exists()) {
fileDetailRequestCount++;
}
}
CVSEvent event = new EnhancedMessageEvent(this,
EnhancedMessageEvent.REQUESTS_COUNT,
new Integer(fileDetailRequestCount));
getEventManager().fireCVSEvent(event);
}
LoggedDataOutputStream dos = connection.getOutputStream();
loggedDataOutputStream = dos;
// this list stores stream modification requests, each to be called
// to modify the input stream the next time we need to process a
// response
List streamModifierRequests = new LinkedList();
// sending files does not seem to allow compression
transmitFileHandler = getUncompressedFileHandler();
for (Iterator it = requests.iterator(); it.hasNext();) {
if (abort) {
throw new CommandAbortedException("Aborted during request processing", // NOI18N
CommandException.getLocalMessage("Client.commandAborted", null)); //NOI18N
}
final Request request = (Request)it.next();
if (request instanceof GzipFileContentsRequest) {
if (dontUseGzipFileHandler) {
stderr.println("Warning: The server is not supporting gzip-file-contents request, no compression is used.");
continue;
}
}
// skip the root request if already sent
if (request instanceof RootRequest) {
if (filterRootRequest) {
continue;
} else { // Even if we should not filter the RootRequest now, we must filter all successive RootRequests
filterRootRequest = true;
}
}
// send request to server
String requestString = request.getRequestString();
dos.writeBytes(requestString);
// we must modify the outputstream now, but defer modification
// of the inputstream until we are about to read a response.
// This is because some modifiers (e.g. gzip) read the header
// on construction, and obviously no header is present when
// no response has been sent
request.modifyOutputStream(connection);
if (request.modifiesInputStream()) {
streamModifierRequests.add(request);
}
dos = connection.getOutputStream();
FileDetails fileDetails = request.getFileForTransmission();
if (fileDetails != null) {
final File file = fileDetails.getFile();
// only transmit the file if it exists! When committing
// a remove request you cannot transmit the file
if (file.exists()) {
Logger.logOutput(new String("\n").getBytes("utf8")); // NOI18N
if (fireEnhancedEvents) {
CVSEvent event = new EnhancedMessageEvent(this,
EnhancedMessageEvent.FILE_SENDING,
file);
getEventManager().fireCVSEvent(event);
fileDetailRequestCount--;
}
if (fileDetails.isBinary()) {
transmitFileHandler.transmitBinaryFile(file, dos);
}
else {
transmitFileHandler.transmitTextFile(file, dos);
}
if (fireEnhancedEvents && fileDetailRequestCount == 0) {
CVSEvent event = new EnhancedMessageEvent(this,
EnhancedMessageEvent.REQUESTS_SENT,
"Ok"); // NOI18N
getEventManager().fireCVSEvent(event);
}
}
}
if (request.isResponseExpected()) {
dos.flush();
// now perform the deferred modification of the input stream
Iterator modifiers = streamModifierRequests.iterator();
while (modifiers.hasNext()) {
System.err.println("Modifying the inputstream..."); // NOI18N
final Request smRequest = (Request)modifiers.next();
System.err.println("Request is a: " + // NOI18N
smRequest.getClass().getName());
smRequest.modifyInputStream(connection);
}
streamModifierRequests.clear();
handleResponse();
}
}
dos.flush();
transmitFileHandler = null;
}
private ResponseFactory getResponseFactory() {
if (responseFactory == null) {
responseFactory = new ResponseFactory();
}
return responseFactory;
}
/**
* Handle the response from a request.
* @throws ResponseException if there is a problem reading the response
*/
private void handleResponse()
throws ResponseException, CommandAbortedException {
try {
LoggedDataInputStream dis = connection.getInputStream();
loggedDataInputStream = dis;
int ch = -1;
try {
ch = dis.read();
} catch (InterruptedIOException ex) {
abort();
}
while (!abort && ch != -1) {
StringBuffer responseNameBuffer = new StringBuffer();
// read in the response name
while (ch != -1 &&
(char)ch != '\n' &&
(char)ch != ' ') {
responseNameBuffer.append((char)ch);
try {
ch = dis.read();
} catch (InterruptedIOException ex) {
abort();
break;
}
}
String responseString = responseNameBuffer.toString();
Response response = getResponseFactory().createResponse(responseString);
//Logger.logInput(new String("<" + responseString + " processing start>\n").getBytes()); // NOI18N
response.process(dis, this);
boolean terminal = response.isTerminalResponse();
// handle SpecialResponses
if (terminal && response instanceof ErrorMessageResponse) {
ErrorMessageResponse errorResponce = (ErrorMessageResponse) response;
String errMsg = errorResponce.getMessage();
throw new CommandAbortedException(errMsg, errMsg);
}
//Logger.logInput(new String("<" + responseString + " processed " + terminal + ">\n").getBytes()); // NOI18N
if (terminal || abort) {
break;
}
try {
ch = dis.read();
} catch (InterruptedIOException ex) {
abort();
break;
}
}
if (abort) {
String localMsg = CommandException.getLocalMessage("Client.commandAborted", null); //NOI18N
throw new CommandAbortedException("Aborted during request processing", localMsg); // NOI18N
}
}
catch (EOFException ex) {
throw new ResponseException(ex, ResponseException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (IOException ex) {
throw new ResponseException(ex);
}
}
/**
* Execute a command. Do not forget to initialize the CVS Root on globalOptions first!
* Example:
*
* GlobalOptions options = new GlobalOptions();
* options.setCVSRoot(":pserver:"+userName+"@"+hostName+":"+cvsRoot);
*
* @param command the command to execute
* @param options the global options to use for executing the command
* @throws CommandException if an error occurs when executing the command
* @throws CommandAbortedException if the command is aborted
*/
public boolean executeCommand(Command command, GlobalOptions globalOptions)
throws CommandException, CommandAbortedException, AuthenticationException {
BugLog.getInstance().assertNotNull(command);
BugLog.getInstance().assertNotNull(globalOptions);
this.globalOptions = globalOptions;
getUncompressedFileHandler().setGlobalOptions(globalOptions);
getGzipFileHandler().setGlobalOptions(globalOptions);
try {
eventManager.addCVSListener(command);
command.execute(this, eventManager);
}
finally {
eventManager.removeCVSListener(command);
}
return !command.hasFailed();
}
/**
* Counts {@link #processRequests(java.util.List)}. send and received bytes.
*
* @thread it assumes that client is not run in paralel.
*/
public long getCounter() {
long ret = 0;
if (loggedDataInputStream != null) {
ret += loggedDataInputStream.getCounter();
}
if (loggedDataOutputStream != null) {
ret += loggedDataOutputStream.getCounter();
}
return ret;
}
/**
* Convert a pathname in the CVS sense (see 5.10 in the protocol
* document) into a local absolute pathname for the file.
* @param localDirectory the name of the local directory, relative to the
* directory in which the command was given
* @param repository the full repository name for the file
*/
public String convertPathname(String localDirectory, String repository) {
int lastIndexOfSlash = repository.lastIndexOf('/');
String filename = repository.substring(lastIndexOfSlash + 1);
if (localDirectory.startsWith("./")) { // NOI18N
// remove the dot
localDirectory = localDirectory.substring(1);
}
if (localDirectory.startsWith("/")) { // NOI18N
// remove the leading slash
localDirectory = localDirectory.substring(1);
}
// note that the localDirectory ends in a slash
return getLocalPath() + '/' + localDirectory + filename;
}
/**
* Get the repository path from the connection.
*
* @return the repository path, e.g. /home/bob/cvs. Delegated to the
* Connection in this case
* @see Connection#getRepository()
*/
public String getRepository() {
return connection.getRepository();
}
/**
* Create or update the administration files for a particular file.
* This will create the CVS directory if necessary, and the
* Root and Repository files if necessary. It will also update
* the Entries file with the new entry
* @param localDirectory the local directory, relative to the directory
* in which the command was given, where the file in question lives
* @param repositoryPath the path of the file in the repository, in
* absolute form.
* @param entry the entry object for that file
*/
public void updateAdminData(String localDirectory, String repositoryPath,
Entry entry)
throws IOException {
final String absolutePath = localPath + '/' + localDirectory;
if (repositoryPath.startsWith(getRepository())) {
repositoryPath = repositoryPath.substring(getRepository().length() + 1);
} else {
if (warned == false) {
String warning = "#65188 warning C/S protocol error (section 5.10). It's regurarly observed with cvs 1.12.xx servers.\n"; // NOI18N
warning += " unexpected pathname=" + repositoryPath + " missing root prefix=" + getRepository() + "\n"; // NOI18N
warning += " relaxing, but who knows all consequences...."; // NOI18N
System.err.println(warning);
warned = true;
}
}
adminHandler.updateAdminData(absolutePath, repositoryPath, entry,
globalOptions);
}
/**
* Set the modified date of the next file to be written. The next call
* to writeFile will use this date.
* @param modifiedDate the date the file should be marked as modified
*/
public void setNextFileDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
/**
* Get the modified date for the next file.
* @return the date and then null the instance variable.
*/
public Date getNextFileDate() {
//
// We null the instance variable so that future calls will not
// retrieve a date specified for a previous file
//
Date copy = modifiedDate;
modifiedDate = null;
return copy;
}
/**
* Get the Entry for the specified file, if one exists.
* @param f the file
* @throws IOException if the Entries file cannot be read
*/
public Entry getEntry(File f)
throws IOException {
return adminHandler.getEntry(f);
}
/**
* Get the entries for a specified directory.
* @param directory the directory for which to get the entries
* @return an iterator of Entry objects
*/
public Iterator getEntries(File directory)
throws IOException {
return adminHandler.getEntries(directory);
}
public boolean exists(File file) {
return adminHandler.exists(file);
}
/**
* Get the repository path for a given directory, for example in
* the directory /home/project/foo/bar, the repository directory
* might be /usr/cvs/foo/bar. The repository directory is commonly
* stored in the file Repository
in the CVS directory on
* the client (this is the case in the standard CVS command-line tool).
*
* If no CVS/Repository
file was found, the specified directory,
* the localpath are used to "guess" the repository path.
*
* @param directory the directory
*/
public String getRepositoryForDirectory(String directory)
throws IOException {
try {
String repository = adminHandler.getRepositoryForDirectory(
directory, getRepository());
return repository;
}
catch (IOException ex) {
// an IOException is thrown, if the adminHandler can't detect the repository
// by reading the CVS/Repository file, e.g. when checking out into a new directory
try {
directory = new File(directory).getCanonicalPath();
} catch (IOException ioex) {}
directory = directory.replace('\\', '/');
while (directory.endsWith("/")) { // NOI18N
directory = directory.substring(0, directory.length() - 1);
}
// must also canonicalize 'localPath' to be in sync with 'directory'
String localPathCanonical = getLocalPath();
try {
localPathCanonical = new File(getLocalPath()).getCanonicalPath();
} catch (IOException ioex) {}
localPathCanonical = localPathCanonical.replace('\\', '/');
while (localPathCanonical.endsWith("/")) { // NOI18N
localPathCanonical = localPathCanonical.substring(0, localPathCanonical.length() - 1);
}
int localPathLength = localPathCanonical.length();
String repository;
if (directory.length() >= localPathLength) {
repository = getRepository() + directory.substring(localPathLength);
} else { // Asking for some folder upon the local working path
repository = getRepository();
}
return repository;
}
}
public String getRepositoryForDirectory(File directory) throws IOException {
return adminHandler.getRepositoryForDirectory(directory.getAbsolutePath(), getRepository());
}
/**
* Set the Entry for the specified file.
* @param file the file
* @param entry the new entry
* @throws IOException if an error occurs writing the details
*/
public void setEntry(File file, Entry entry)
throws IOException {
adminHandler.setEntry(file, entry);
}
/**
* Remove the Entry for the specified file.
* @param file the file whose entry is to be removed
* @throws IOException if an error occurs writing the Entries file
*/
public void removeEntry(File file)
throws IOException {
adminHandler.removeEntry(file);
}
/**
* Remove the specified file from the local disk.
* If the file does not exist, the operation does nothing.
* @param pathname the full path to the file to remove
* @throws IOException if an IO error occurs while removing the file
*/
public void removeLocalFile(String pathname)
throws IOException {
transmitFileHandler.removeLocalFile(pathname);
}
/**
* Removes the specified file determined by pathName and repositoryName.
* In this implementation the filename from repositoryPath is added
* to the localpath (which doesn't have the filename in it) and that file is deleted.
*/
public void removeLocalFile(String pathName, String repositoryName)
throws IOException {
int ind = repositoryName.lastIndexOf('/');
if (ind <= 0) {
return;
}
String fileName = repositoryName.substring(ind + 1);
String localFile = pathName + fileName;
File fileToDelete = new File(getLocalPath(), localFile);
removeLocalFile(fileToDelete.getAbsolutePath());
removeEntry(fileToDelete);
}
public void copyLocalFile(String pathname, String newName)
throws IOException {
transmitFileHandler.copyLocalFile(pathname, newName);
}
/**
* Get the CVS event manager. This is generally called by response handlers
* that want to fire events.
* @return the eventManager
*/
public EventManager getEventManager() {
return eventManager;
}
/**
* Get the global options that are set to this client.
* Individual commands can get the global options via this method.
*/
public GlobalOptions getGlobalOptions() {
return globalOptions;
}
/**
* Call this method to abort the current command. The command will be
* aborted at the next suitable time
*/
public synchronized void abort() {
abort = true;
}
/**
* Get all the files contained within a given
* directory that are known to CVS.
* @param directory the directory to look in
* @return a set of all files.
*/
public Set getAllFiles(File directory) throws IOException {
return adminHandler.getAllFiles(directory);
}
public void setIgnoreFileFilter(IgnoreFileFilter ignoreFileFilter) {
this.ignoreFileFilter = ignoreFileFilter;
}
public IgnoreFileFilter getIgnoreFileFilter() {
return ignoreFileFilter;
}
public boolean shouldBeIgnored(File directory, String noneCvsFile) {
if (ignoreFileFilter != null) {
return ignoreFileFilter.shouldBeIgnored(directory, noneCvsFile);
}
return false;
}
/**
* Checks for presence of CVS/Tag file and returns it's value.
* @return the value of CVS/Tag file for the specified directory
* null if file doesn't exist
*/
public String getStickyTagForDirectory(File directory) {
return adminHandler.getStickyTagForDirectory(directory);
}
/**
* This method is called when a response for the ValidRequests request
* is received.
* @param requests A List of requests that is valid for this CVS server
* separated by spaces.
*/
public void setValidRequests(String requests)
{
// We need to tokenize the requests and add it to our map
StringTokenizer tokenizer = new StringTokenizer(requests);
String token;
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
// we just add an object with the corresponding request
// as the key.
validRequests.put(token, this);
}
}
private int fillInitialRequests(List requests) {
int pos = 0;
requests.add(pos++, new RootRequest(getRepository()));
requests.add(pos++, new UseUnchangedRequest());
requests.add(pos++, new ValidRequestsRequest());
requests.add(pos++, new ValidResponsesRequest());
return pos;
}
/** This method is called by WrapperSendResponse for each wrapper setting sent
* back by the CVS server
* @param pattern A StringPattern indicating the pattern for which the
* wrapper applies
* @param option A KeywordSubstituionOption corresponding to the setting
*/
public void addWrapper(StringPattern pattern, KeywordSubstitutionOptions option) {
if (wrappersMap == null) {
throw new IllegalArgumentException("This method should be called "+
"by WrapperSendResponse only.");
}
wrappersMap.put(pattern, option);
}
/** Returns the wrappers map associated with the CVS server
* The map is valid only after the connection is established
*/
public Map getWrappersMap() throws CommandException {
if (wrappersMap == null) {
wrappersMap = new HashMap();
ArrayList requests = new ArrayList();
requests.add(new WrapperSendRequest());
boolean isFirst = isFirstCommand();
try {
processRequests(requests);
} catch (Exception ex) {
throw new CommandException(ex, "An error during obtaining server wrappers.");
} finally {
// Do not alter isFirstCommand property
setIsFirstCommand(isFirst);
}
wrappersMap = Collections.unmodifiableMap(wrappersMap);
}
return wrappersMap;
}
/**
* Factory for creating clients.
*/
public static interface Factory {
/**
* Creates new client instance. Never null.
* It uses fresh connection.
*/
Client createClient();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/ClientServices.java 0000644 0001753 0000144 00000021767 11175406776 025657 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.file.*;
import org.netbeans.lib.cvsclient.request.*;
import org.netbeans.lib.cvsclient.response.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* Clients that provide the ability to execute commands must implement this
* interface. All commands use this interface to get details about the
* environment in which it is being run, and to perform administrative
* functions such as obtaining Entry lines for specified files.
* @author Robert Greig
*/
public interface ClientServices {
/**
* Process all the requests.
*
* @param requests the requets to process
*/
void processRequests(List requests) throws IOException,
UnconfiguredRequestException, ResponseException,
CommandAbortedException;
/**
* Get the repository used for this connection.
*
* @return the repository, for example /home/bob/cvs
*/
String getRepository();
/**
* Get the repository path for a given directory, for example in
* the directory /home/project/foo/bar, the repository directory
* might be /usr/cvs/foo/bar. The repository directory is commonly
* stored in the file Repository
in the CVS directory on
* the client. (This is the case in the standard CVS command-line tool)
*
* @param directory the directory
*/
String getRepositoryForDirectory(String directory)
throws IOException;
/**
* Semantically equivalent to {@link #getRepositoryForDirectory(String)} but does not try to recover from
* missing CVS/Repository file.
*
* @param directory the directory to get repository for
* @return repository path that corresponds to the given local working directory or null if local directory
* is not versioned or does not exist
* @throws IOException if the repository cannot be determined by reading CVS/Repository file
*/
String getRepositoryForDirectory(File directory) throws IOException;
/**
* Get the local path that the command is executing in.
*
* @return the local path
*/
String getLocalPath();
/**
* Get the Entry for the specified file, if one exists.
*
* @param file the file
*
* @throws IOException if the Entries file cannot be read
*/
Entry getEntry(File file) throws IOException;
/**
* Get the entries for a specified directory.
*
* @param directory the directory for which to get the entries
*
* @return an iterator of Entry objects
*/
Iterator getEntries(File directory) throws IOException;
/**
* Create or update the administration files for a particular file
* This will create the CVS directory if necessary, and the
* Root and Repository files if necessary. It will also update
* the Entries file with the new entry
*
* @param localDirectory the local directory, relative to the directory
* in which the command was given, where the file in
* question lives
* @param entry the entry object for that file
*
* @throws IOException if there is an error writing the files
*/
void updateAdminData(String localDirectory, String repositoryPath,
Entry entry)
throws IOException;
/**
* Get all the files contained within a given
* directory that are known to CVS.
*
* @param directory the directory to look in
*
* @return a set of all files.
*/
Set getAllFiles(File directory) throws IOException;
/**
* Returns true if no command was sent before.
* This is used, because the server rejects some doubled commands.
*/
boolean isFirstCommand();
/**
* Set whether this is the first command. Normally you do not need to set
* this yourself - after execution the first command will have set this to
* false.
*/
void setIsFirstCommand(boolean first);
/**
* Removes the Entry for the specified file.
*/
void removeEntry(File file) throws IOException;
/**
* Sets the specified IgnoreFileFilter to use to ignore non-cvs files.
* TS, 2001-11-23: really needed in the interface (it's never used)?
*/
void setIgnoreFileFilter(IgnoreFileFilter filter);
/**
* Returns the IgnoreFileFilter used to ignore non-cvs files.
* TS, 2001-11-23: really needed in the interface (it's never used)?
*/
IgnoreFileFilter getIgnoreFileFilter();
/**
* Returnes true to indicate, that the file specified by directory and nonCvsFile
* should be ignored.
*/
boolean shouldBeIgnored(File directory, String nonCvsFile);
//
// allow the user of the Client to define the FileHandlers
//
/**
* Set the uncompressed file handler.
*/
void setUncompressedFileHandler(FileHandler handler);
/**
* Set the handler for Gzip data.
*/
void setGzipFileHandler(FileHandler handler);
/**
* Checks for presence of CVS/Tag file and returns it's value.
*
* @return the value of CVS/Tag file for the specified directory
* null if file doesn't exist
*/
String getStickyTagForDirectory(File directory);
/**
* Ensures, that the connection is open.
*
* @throws AuthenticationException if it wasn't possible to connect
*/
void ensureConnection() throws AuthenticationException;
/**
* Returns the wrappers map associated with the CVS server
* The map is valid only after the connection is established
*/
Map getWrappersMap() throws CommandException;
/**
* Get the global options that are set to this client.
* Individual commands can get the global options via this method.
*/
GlobalOptions getGlobalOptions();
/**
* Tests for existence of the given file. Normally this method
* delegates to File.exists() but it may also return true for files
* that exists only virtually (in memory). Is such case the file/directory
* will not exist on disk but its metadata will be available via getEntries() methods.
*
* @param file file to test for existence
* @return true if the file exists, false otherwise
*/
boolean exists(File file);
/**
* Tests whether command execution should be aborted. Commands are encouraged to regulary
* poll this value if they expect to block for a long time in their code.
*
* @return true if currently running command should abort, false otherwise
*/
boolean isAborted();
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/admin/ 0000755 0001753 0000144 00000000000 11175434236 023135 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/admin/AdminHandler.java 0000644 0001753 0000144 00000014221 11175406776 026336 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.admin;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
/**
* Handles the maintaining and reading of administration information on the
* local machine. The standard CVS client does this by putting various files in
* a CVS directory underneath each checked-out directory. How the files are
* laid out and managed is not specified by the protocol document. Hence it
* is envisaged that, eventually, a client could add additional files for
* higher performance or even change the mechanism for storing the information
* completely.
* @author Robert Greig
*/
public interface AdminHandler {
/**
* Create or update the administration files for a particular file.
* This will create the CVS directory if necessary, and the
* Root and Repository files if necessary. It will also update
* the Entries file with the new entry
* @param localDirectory the local directory where the file in question
* lives (the absolute path). Must not end with a slash.
* @param repositoryPath the path of the file in the repository
* @param entry the entry object for that file
* @param globalOptions the global command options
*/
void updateAdminData(String localDirectory, String repositoryPath,
Entry entry, GlobalOptions globalOptions)
throws IOException;
/**
* Get the Entry for the specified file, if one exists
* @param file the file
* @throws IOException if the Entries file cannot be read
*/
Entry getEntry(File file) throws IOException;
/**
* Get the entries for a specified directory.
* @param directory the directory for which to get the entries
* @return an iterator of Entry objects
*/
Iterator getEntries(File directory) throws IOException;
/**
* Set the Entry for the specified file
* @param file the file
* @param entry the new entry
* @throws IOException if an error occurs writing the details
*/
void setEntry(File file, Entry entry) throws IOException;
/**
* Get the repository path for a given directory, for example in
* the directory /home/project/foo/bar, the repository directory
* might be /usr/cvs/foo/bar. The repository directory is commonly
* stored in the file
Repository
in the CVS directory on
* the client. (This is the case in the standard CVS command-line tool)
* @param directory the directory
* @param the repository path on the server, e.g. /home/bob/cvs. Must not
* end with a slash.
*/
String getRepositoryForDirectory(String directory, String repository)
throws IOException;
/**
* Remove the Entry for the specified file
* @param file the file whose entry is to be removed
* @throws IOException if an error occurs writing the Entries file
*/
void removeEntry(File file) throws IOException;
/**
* Get all the files contained within a given
* directory that are known to CVS.
* @param directory the directory to look in
* @return a set of all files.
*/
Set getAllFiles(File directory) throws IOException;
/**
* Checks for presence of CVS/Tag file and returns it's value.
* @return the value of CVS/Tag file for the specified directory (including leading "T")
* null if file doesn't exist
*/
String getStickyTagForDirectory(File directory);
/**
* Tests for existence of the given file. Normally this method
* delegates to File.exists() but it may also return true for files
* that exists only virtually (in memory). Is such case the file/directory
* will not exist on disk but its metadata will be available via getEntries() methods.
*
* @param file file to test for existence
* @return true if the file exists, false otherwise
*/
boolean exists(File file);
} netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/admin/DateComparator.java 0000644 0001753 0000144 00000006717 11175406776 026730 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.admin;
/**
* A class for comparing the file's date and the CVS/Entries date.
*
* @author Thomas Singer
* @version Sep 29, 2001
*/
public class DateComparator {
private static final long SECONDS_PER_HOUR = 3600;
private static final DateComparator singleton = new DateComparator();
/**
* Returns an instance of a DateComparator.
*/
public static DateComparator getInstance() {
return singleton;
}
/**
* This class is a singleton. There is no need to subclass or
* instantiate it outside.
*/
private DateComparator() {
}
/**
* Compares the specified dates, whether they should be treated as equal.
* Returns true to indicate equality.
*/
public boolean equals(final long fileTime, final long entryTime) {
final long fileTimeSeconds = fileTime / 1000;
final long entryTimeSeconds = entryTime / 1000;
final long difference = Math.abs(fileTimeSeconds - entryTimeSeconds);
// differences smaller than 1 second are treated as equal to catch rounding errors
if (difference < 1) {
return true;
}
// 1-hour-differences (caused by daylight-saving) are treated as equal
if (difference >= SECONDS_PER_HOUR - 1
&& difference <= SECONDS_PER_HOUR + 1) {
return true;
}
return false;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/admin/StandardAdminHandler.java 0000644 0001753 0000144 00000073430 11175406776 030026 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.admin;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.file.FileUtils;
/**
* A handler for administrative information that maintains full compatibility
* with the one employed by the original C implementation of a CVS client.
* This implementation strives to provide complete compatibility with
* the standard CVS client, so that operations on locally checked-out
* files can be carried out by either this library or the standard client
* without causing the other to fail. Any such failure should be considered
* a bug in this library.
* @author Robert Greig
*/
public class StandardAdminHandler implements AdminHandler {
private static final Object ksEntries = new Object();
private static Runnable t9yBeforeRename;
/**
* Create or update the administration files for a particular file.
* This will create the CVS directory if necessary, and the
* Root and Repository files if necessary. It will also update
* the Entries file with the new entry
* @param localDirectory the local directory where the file in question
* lives (the absolute path). Must not end with a slash.
* @param entry the entry object for that file. If null, there is no
* entry to add, and the Entries file will not have any entries added to
* it (it will be created if it does not exist, however).
*/
public void updateAdminData(String localDirectory, String repositoryPath,
Entry entry, GlobalOptions globalOptions)
throws IOException {
// add this directory to the list of those to check for emptiness if
// the prune option is specified
final File CVSdir = new File(localDirectory, "CVS"); //NOI18N
CVSdir.mkdirs();
// now ensure that the Root and Repository files exist
File rootFile = new File(CVSdir, "Root"); //NOI18N
if (!rootFile.exists()) {
PrintWriter w = new PrintWriter(new FileWriter(rootFile));
try {
w.println(globalOptions.getCVSRoot());
} finally {
w.close();
}
}
File repositoryFile = new File(CVSdir, "Repository"); //NOI18N
if (!repositoryFile.exists()) {
PrintWriter w = new PrintWriter(new FileWriter(repositoryFile));
try {
if (entry != null && !entry.isDirectory()) {
// If there is a file entry, the repository path is for a file!
int length = entry.getName().length();
repositoryPath = repositoryPath.substring(0, repositoryPath.length() - length);
}
if (repositoryPath.endsWith("/")) { //NOI18N
repositoryPath = repositoryPath.substring(0,
repositoryPath.length() - 1);
}
if (repositoryPath.length() == 0) {
repositoryPath = "."; //NOI18N
}
// we write out the relative path to the repository file
w.println(repositoryPath);
} finally {
w.close();
}
}
final File entriesFile = new File(CVSdir, "Entries"); //NOI18N
// We assume that if we do not have an Entries file, we need to add
// the file to the parent CVS directory as well as create the
// Entries file for this directory
if (entriesFile.createNewFile()) {
// need to know if we had to create any directories so that we can
// update the CVS/Entries file in the *parent* director
addDirectoryToParentEntriesFile(CVSdir);
// We have created a new Entries file, so put a D in it to
// indicate that we understand directories.
// TODO: investigate what the point of this is. The command-line
// CVS client does it
final Writer w = new BufferedWriter(new FileWriter(entriesFile));
try {
w.write("D"); //NOI18N
} finally {
w.close();
}
}
// Update the Entries file
if (entry != null) {
updateEntriesFile(entriesFile, entry);
}
}
/**
* Simply delegates to File.exists(), does not provide any virtual files.
*
* @param file file to test for existence
* @return true if the file exists on disk, false otherwise
*/
public boolean exists(File file) {
return file.exists();
}
/**
* Add a directory entry to the parent directory's Entries file, if it
* exists. Any line containing only a D is deleted from the parent
* Entries file.
* @param CVSdir the full path to the CVS directory for the directory
* that has just been added
*/
private void addDirectoryToParentEntriesFile(File CVSdir)
throws IOException {
synchronized (ksEntries) {
File parentCVSEntries = seekEntries(CVSdir.getParentFile().getParentFile());
// only update if the file exists. The file will not exist in the
// case where this is the top level of the module
if (parentCVSEntries != null) {
final File directory = parentCVSEntries.getParentFile();
final File tempFile = new File(directory, "Entries.Backup"); //NOI18N
tempFile.createNewFile();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(parentCVSEntries));
writer = new BufferedWriter(new FileWriter(tempFile));
String line;
// As in the updateEntriesFile method the new Entry
// only may be written, if it does not exist
boolean written = false;
Entry directoryEntry = new Entry();
directoryEntry.setName(CVSdir.getParentFile().getName());
directoryEntry.setDirectory(true);
while ((line = reader.readLine()) != null) {
if (line.trim().equals("D")) { //NOI18N
// do not write out this line
continue;
}
final Entry currentEntry = new Entry(line);
if (currentEntry.getName() != null
&& currentEntry.getName().equals(directoryEntry.getName())) {
writer.write(directoryEntry.toString());
written = true;
}
else {
writer.write(line);
}
writer.newLine();
}
if (!written) {
writer.write(directoryEntry.toString());
writer.newLine();
}
} finally {
try {
if (writer != null) {
writer.close();
}
} finally {
if (reader != null) {
reader.close();
}
}
}
if (t9yBeforeRename != null) t9yBeforeRename.run();
FileUtils.renameFile(tempFile, parentCVSEntries);
}
}
}
/**
* Update the specified Entries file with a given entry
* This method currently does the following, in order:
*
- Create a new temporary file, Entries.temp
* - Iterate through each line of the original file, checking
* if it matches the entry of the entry to be updated. If not, simply
* copy the line otherwise write the new entry and discard the old one
* - Once all lines have been written, close both files
* - Move the original file to Entries.temp2
* - Move the file Entries.temp to Entries
* - Delete Entries.temp2
* Note that in the case where the Entries file does not exist, it
* is simply created and the entry appended immediately.
* This all ensures that if a failure occurs at any stage, the original
* Entries file can be retrieved
* @param originalFile the original Entries file, which need not exist yet
* @param entry the specific entry to update
* @throws IOException if an error occurs writing the files
*/
private void updateEntriesFile(File originalFile, Entry entry)
throws IOException {
synchronized (ksEntries) {
final File directory = originalFile.getParentFile();
final File tempFile = new File(directory, "Entries.Backup"); //NOI18N
tempFile.createNewFile();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(originalFile));
writer = new BufferedWriter(new FileWriter(tempFile));
String line;
// indicates whether we have written the entry that was passed in
// if we finish copying the file without writing it, then it is
// a new entry and must simply be append at the end
boolean written = false;
while ((line = reader.readLine()) != null) {
final Entry currentEntry = new Entry(line);
if ((currentEntry.getName() != null) &&
currentEntry.getName().equals(entry.getName())) {
writer.write(entry.toString());
written = true;
}
else {
writer.write(line);
}
writer.newLine();
}
if (!written) {
writer.write(entry.toString());
writer.newLine();
}
} finally {
try {
if (writer != null) {
writer.close();
}
} finally {
if (reader != null) {
reader.close();
}
}
}
if (t9yBeforeRename != null) t9yBeforeRename.run();
FileUtils.renameFile(tempFile, originalFile);
}
}
/**
* Get the Entry for the specified file, if one exists
* @param f the file
* @throws IOException if the Entries file cannot be read
*/
public Entry getEntry(File file) throws IOException {
final File entriesFile = seekEntries(file.getParentFile()); //NOI18N
// if there is no Entries file we cannot very well get any Entry
// from it
if (entriesFile == null) {
return null;
}
processEntriesDotLog(new File(file.getParent(), "CVS")); //NOI18N
BufferedReader reader = null;
Entry entry = null;
boolean found = false;
try {
reader = new BufferedReader(new FileReader(entriesFile));
String line;
while (!found && ((line = reader.readLine()) != null)) {
entry = new Entry(line);
// can have a name of null in the case of the single
// D entry line spec, indicating no subdirectories
if (entry.getName() != null) {
// file equality and string equality are not the same thing
File entryFile = new File(file.getParentFile(), entry.getName());
found = entryFile.equals(file);
}
}
}
finally {
if (reader != null) {
reader.close();
}
}
if (!found) {
return null;
}
return entry;
}
/**
* Get the entries for a specified directory.
* @param directory the directory for which to get the entries
* @return an array of Entry objects
*/
public Entry[] getEntriesAsArray(File directory)
throws IOException {
List entries = new LinkedList();
final File entriesFile = seekEntries(directory);
// if there is no Entries file we just return the empty iterator
if (entriesFile == null) {
return new Entry[0];
}
processEntriesDotLog(new File(directory, "CVS")); //NOI18N
BufferedReader reader = null;
Entry entry = null;
try {
reader = new BufferedReader(new FileReader(entriesFile));
String line;
while ((line = reader.readLine()) != null) {
entry = new Entry(line);
// can have a name of null in the case of the single
// D entry line spec, indicating no subdirectories
if (entry.getName() != null) {
entries.add(entry);
}
}
}
finally {
if (reader != null) {
reader.close();
}
}
Entry[] toReturnArray = new Entry[entries.size()];
toReturnArray = (Entry[])entries.toArray(toReturnArray);
return toReturnArray;
}
/**
* Get the entries for a specified directory.
* @param directory the directory for which to get the entries (CVS/Entries is appended)
* @return an iterator of Entry objects
*/
public Iterator getEntries(File directory)
throws IOException {
List entries = new LinkedList();
final File entriesFile = seekEntries(directory);
// if there is no Entries file we just return the empty iterator
if (entriesFile == null) {
return entries.iterator();
}
processEntriesDotLog(new File(directory, "CVS")); //NOI18N
BufferedReader reader = null;
Entry entry = null;
try {
reader = new BufferedReader(new FileReader(entriesFile));
String line;
while ((line = reader.readLine()) != null) {
entry = new Entry(line);
// can have a name of null in the case of the single
// D entry line spec, indicating no subdirectories
if (entry.getName() != null) {
entries.add(entry);
}
}
}
finally {
if (reader != null) {
reader.close();
}
}
return entries.iterator();
}
/**
* Set the Entry for the specified file
* @param f the file whose entry is being updated
* @throws IOException if an error occurs writing the details
*/
public void setEntry(File file, Entry entry)
throws IOException {
String parent = file.getParent();
File entriesFile = seekEntries(parent);
if (entriesFile == null) {
entriesFile = new File(parent, "CVS/Entries"); //NOI18N
}
processEntriesDotLog(new File(parent, "CVS")); //NOI18N
updateEntriesFile(entriesFile, entry);
}
/**
* Remove the Entry for the specified file
* @param f the file whose entry is to be removed
* @throws IOException if an error occurs writing the Entries file
*/
public void removeEntry(File file) throws IOException {
synchronized (ksEntries) {
final File entriesFile = seekEntries(file.getParent());
// if there is no Entries file we cannot very well remove an Entry
// from it
if (entriesFile == null) {
return;
}
processEntriesDotLog(new File(file.getParent(), "CVS")); //NOI18N
final File directory = file.getParentFile();
final File tempFile = new File(directory, "Entries.Backup"); //NOI18N
tempFile.createNewFile();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(entriesFile));
writer = new BufferedWriter(new FileWriter(tempFile));
String line;
// allows us to determine whether we need to put in a "D" line. We do
// that if we remove the last directory from the Entries file
boolean directoriesExist = false;
while ((line = reader.readLine()) != null) {
final Entry currentEntry = new Entry(line);
if ((currentEntry.getName() != null) &&
!currentEntry.getName().equals(file.getName())) {
writer.write(currentEntry.toString());
writer.newLine();
directoriesExist = directoriesExist ||
currentEntry.isDirectory();
}
}
if (!directoriesExist) {
writer.write("D"); //NOI18N
writer.newLine();
}
} finally {
try {
if (writer != null) {
writer.close();
}
} finally {
if (reader != null) {
reader.close();
}
}
}
if (t9yBeforeRename != null) t9yBeforeRename.run();
FileUtils.renameFile(tempFile, entriesFile);
}
}
/**
* Get the repository path for a given directory, for example in
* the directory /home/project/foo/bar, the repository directory
* might be /usr/cvs/foo/bar. The repository directory is commonly
* stored in the file Repository
in the CVS directory on
* the client. (This is the case in the standard CVS command-line tool).
* However, the path stored in that file is relative to the repository
* path
* @param directory the directory
* @param the repository path on the server, e.g. /home/bob/cvs. Must not
* end with a slash.
*/
public String getRepositoryForDirectory(String directory,
String repository)
throws IOException {
// if there is no "CVS/Repository" file, try to search up the file-
// hierarchy
File repositoryFile = null;
String repositoryDirs = ""; //NOI18N
File dirFile = new File(directory);
while (true) {
// if there is no Repository file we cannot very well get any
// repository from it
if (dirFile == null
|| dirFile.getName().length() == 0
|| !dirFile.exists()) {
throw new FileNotFoundException("Repository file not found " + //NOI18N
"for directory " + directory); //NOI18N
}
repositoryFile = new File(dirFile, "CVS/Repository"); //NOI18N
if (repositoryFile.exists()) {
break;
}
repositoryDirs = '/' + dirFile.getName() + repositoryDirs;
dirFile = dirFile.getParentFile();
}
BufferedReader reader = null;
// fileRepository is the value of the repository read from the
// Repository file
String fileRepository = null;
try {
reader = new BufferedReader(new FileReader(repositoryFile));
fileRepository = reader.readLine();
}
finally {
if (reader != null) {
reader.close();
}
}
if (fileRepository == null) {
fileRepository = ""; //NOI18N
}
fileRepository += repositoryDirs;
// absolute repository path ?
if (fileRepository.startsWith("/")) { //NOI18N
return fileRepository;
}
// #69795 'normalize' repository path
if (fileRepository.startsWith("./")) { // NOI18N
fileRepository = fileRepository.substring(2);
}
// otherwise the cvs is using relative repository path
// must be a forward slash, regardless of the local filing system
return repository + '/' + fileRepository;
}
/**
* Update the Entries file using information in the Entries.Log file
* (if present). If Entries.Log is not present, this method does
* nothing.
* @param directory the directory that contains the Entries file
* @throws IOException if an error occurs reading or writing the files
*/
private void processEntriesDotLog(File directory) throws IOException {
synchronized (ksEntries) {
final File entriesDotLogFile = new File(directory, "Entries.Log"); //NOI18N
if (!entriesDotLogFile.exists()) {
return;
}
BufferedReader reader = new BufferedReader(new FileReader(
entriesDotLogFile));
// make up a list of changes to be made based on what is in
// the .log file. Then apply them all later
List additionsList = new LinkedList();
HashSet removalSet = new HashSet();
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.startsWith("A ")) { //NOI18N
final Entry entry = new Entry(line.substring(2));
additionsList.add(entry);
}
else if (line.startsWith("R ")) { //NOI18N
final Entry entry = new Entry(line.substring(2));
removalSet.add(entry.getName());
}
// otherwise ignore the line since we don't understand it
}
} finally {
reader.close();
}
if ((additionsList.size() > 0) || (removalSet.size() > 0)) {
final File backup = new File(directory, "Entries.Backup"); //NOI18N
final BufferedWriter writer = new BufferedWriter(new FileWriter(
backup));
final File entriesFile = new File(directory, "Entries"); //NOI18N
reader = new BufferedReader(new FileReader(entriesFile));
try {
// maintain a count of the number of directories so that
// we know whether to write the "D" line
int directoryCount = 0;
while ((line = reader.readLine()) != null) {
// we will write out the directory "understanding" line
// later, if necessary
if (line.trim().equals("D")) { //NOI18N
continue;
}
final Entry entry = new Entry(line);
if (entry.isDirectory()) {
directoryCount++;
}
if (!removalSet.contains(entry.getName())) {
writer.write(entry.toString());
writer.newLine();
if (entry.isDirectory()) {
directoryCount--;
}
}
}
Iterator it = additionsList.iterator();
while (it.hasNext()) {
final Entry entry = (Entry)it.next();
if (entry.isDirectory()) {
directoryCount++;
}
writer.write(entry.toString());
writer.newLine();
}
if (directoryCount == 0) {
writer.write("D"); //NOI18N
writer.newLine();
}
} finally {
try {
reader.close();
} finally {
writer.close();
}
}
if (t9yBeforeRename != null) t9yBeforeRename.run();
FileUtils.renameFile(backup, entriesFile);
}
entriesDotLogFile.delete();
}
}
/**
* Get all the files contained within a given
* directory that are known to CVS.
* @param directory the directory to look in
* @return a set of all files.
*/
public Set getAllFiles(File directory) throws IOException {
TreeSet fileSet = new TreeSet();
BufferedReader reader = null;
try {
final File entriesFile = seekEntries(directory); //NOI18N
// if for any reason we don't have an Entries file just return
// with the empty set.
if (entriesFile == null) {
return fileSet; // Premature return
}
reader = new BufferedReader(new FileReader(entriesFile));
String line;
while ((line = reader.readLine()) != null) {
final Entry entry = new Entry(line);
if (entry.getName() != null) {
final File f = new File(directory, entry.getName());
if (f.isFile()) {
fileSet.add(f);
}
}
}
}
finally {
if (reader != null) {
reader.close();
}
}
return fileSet;
}
// XXX where is pairing setStickyTagForDirectory?
/**
* Checks for presence of CVS/Tag file and returns it's value.
* @return the value of CVS/Tag file for the specified directory
* null if file doesn't exist
*/
public String getStickyTagForDirectory(File directory) {
BufferedReader reader = null;
File tagFile = new File(directory, "CVS/Tag"); //NOI18N
try {
reader = new BufferedReader(new FileReader(tagFile));
String tag = reader.readLine();
return tag;
}
catch (IOException ex) {
// silently ignore??
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ex) {
// silently ignore
}
}
}
return null;
}
/**
* If Entries do not exist restore them from backup.
*
* @param folder path where to seek CVS/Entries
* @return CVS/Entries file or null
*/
private static File seekEntries(File folder) {
synchronized(ksEntries) {
File entries = new File(folder, "CVS/Entries"); // NOI18N
if (entries.exists()) {
return entries;
} else {
File backup = new File(folder, "CVS/Entries.Backup"); // NOI18N
if (backup.exists()) {
try {
if (t9yBeforeRename != null) t9yBeforeRename.run();
FileUtils.renameFile(backup, entries);
return entries;
} catch (IOException e) {
// ignore
}
}
}
return null;
}
}
private static File seekEntries(String folder) {
return seekEntries(new File(folder));
}
static void t9yBeforeRenameSync(Runnable run) {
t9yBeforeRename = run;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/admin/Entry.java 0000644 0001753 0000144 00000045035 11175416504 025106 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.admin;
import java.text.*;
import java.util.*;
/**
* The class abstracts the CVS concept of an entry line. The entry
* line is textually of the form:
* / name / version / conflict / options / tag_or_date
*
These are explained in section 5.1 of the CVS protocol 1.10 document.
* @author Robert Greig
*/
public final class Entry {
/**
* The dummy timestamp set the conflict information for added or removed
* files.
*/
public static final String DUMMY_TIMESTAMP = "dummy timestamp"; //NOI18N
public static final String DUMMY_TIMESTAMP_NEW_ENTRY = "dummy timestamp from new-entry"; //NOI18N
public static final String MERGE_TIMESTAMP = "Result of merge"; //NOI18N
/**
* Indicates a sticky tag.
*/
private static final String TAG = "T"; //NOI18N
/**
* Indicates a sticky date.
*/
private static final String DATE = "D"; //NOI18N
/**
* The instance of the date formatter for sticky dates.
*/
private static SimpleDateFormat stickyDateFormatter;
/**
* Returns the instance of the date formatter for sticky dates.
*/
private static SimpleDateFormat getStickyDateFormatter() {
if (stickyDateFormatter == null) {
stickyDateFormatter = new SimpleDateFormat("yyyy.MM.dd.hh.mm.ss"); //NOI18N
}
return stickyDateFormatter;
}
/**
* Indicates a binary file.
*/
private static final String BINARY_FILE = "-kb"; //NOI18N
/**
* Indicates that no user file is meant by the version details
*/
private static final String NO_USER_FILE = ""; //NOI18N
/**
* Indicates that a new user file is meant by the version details
*/
private static final String NEW_USER_FILE = "0"; //NOI18N
/**
* Indicates that the file is to be removed, in the version details
*/
private static final String REMOVE_USER_FILE = "-"; //NOI18N
/**
* Returns the instance of the Last-Modified-Date-Formatter.
*/
public static SimpleDateFormat getLastModifiedDateFormatter() {
SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.US); //NOI18N
df.setTimeZone(getTimeZone());
return df;
}
/**
* All entries times are by defaulf in Zulu/GMT0
*/
public static TimeZone getTimeZone() {
return TimeZone.getTimeZone("GMT"); //NOI18N
}
/**
* Indicates that the file had conflicts.
*/
public static final char HAD_CONFLICTS = '+';
/**
* Indicates that the timestamp matches the file.
*/
public static final char TIMESTAMP_MATCHES_FILE = '=';
/**
* Indicates that the file had conflicts and timestamp matches.
* It likely means unresolved conflict.
*/
public static final String HAD_CONFLICTS_AND_TIMESTAMP_MATCHES_FILE = "+=";
/**
* Initial letter that indicates a directory entry.
*/
private static final String DIRECTORY_PREFIX = "D/";
/**
* The name of the file.
*/
private String name;
/**
* The revision. There are constants defined for no user file, new user
* file and user file has to be removed.
*/
private String revision;
/**
* The conflict information. There are constants defined for indicating
* that conflicts occurred and that the timestamp matches the file
*/
private String conflict;
/**
* The last modified date of the file.
*/
private Date lastModified;
/**
* The options for signifying keyword expansion.
*/
private String options;
/**
* The tag. May be present in place of the date information.
*/
private String tag;
/**
* The date. May be present in place of the tag information.
*/
private Date date;
/**
* Indicates whether the entry is for a directory.
*/
private boolean directory;
/**
* Construct a new Entry from a given entry line.
*/
public Entry(String entryLine) {
init(entryLine);
}
/**
* Construct a new blank Entry.
*/
public Entry() {
}
/**
* Initialise the Entry by parsing an entry line.
* @param entryLine the entry line in standard CVS format
*/
protected void init(String entryLine) {
//System.err.println("Constructing an entry line from: " + entryLine);
// try to parse the entry line, if we get stuck just
// throw an illegal argument exception
if (entryLine.startsWith(DIRECTORY_PREFIX)) {
directory = true;
entryLine = entryLine.substring(1);
}
// first character is a slash, so name is read from position 1
// up to the next slash
final int[] slashPositions = new int[5];
try {
slashPositions[0] = 0;
for (int i = 1; i < 5; i++) {
slashPositions[i] = entryLine.indexOf('/',
slashPositions[i - 1] + 1);
}
// Test if this is a D on its own, a special case indicating that
// directories are understood and there are no subdirectories
// in the current folder
if (slashPositions[1] > 0) {
// note that the parameters to substring are treated as follows:
// (inclusive, exclusive)
name = entryLine.substring(slashPositions[0] + 1,
slashPositions[1]);
revision = entryLine.substring(slashPositions[1] + 1,
slashPositions[2]);
if ((slashPositions[3] - slashPositions[2]) > 1) {
String conflict = entryLine.substring(slashPositions[2] + 1,
slashPositions[3]);
setConflict(conflict);
}
if ((slashPositions[4] - slashPositions[3]) > 1) {
options = entryLine.substring(slashPositions[3] + 1,
slashPositions[4]);
}
if (slashPositions[4] != (entryLine.length() - 1)) {
String tagOrDate = entryLine.substring(slashPositions[4]
+ 1);
if (tagOrDate.startsWith(TAG)) {
setTag(tagOrDate.substring(1));
}
else if (tagOrDate.startsWith(DATE)) {
//TODO process date into something useful
// MK - I didn't notice any time conversions (according to timezone)
// So I just convert it from String to Date and back.
try {
String dateString = tagOrDate.substring(DATE.length());
Date stickyDate = getStickyDateFormatter().
parse(dateString);
setDate(stickyDate);
}
catch (ParseException exc) {
System.err.println("We got another inconsistency in the library's date formatting."); //NOI18N
}
}
}
}
}
catch (Exception e) {
System.err.println("Error parsing entry line: " + e); //NOI18N
e.printStackTrace();
throw new IllegalArgumentException("Invalid entry line: " + //NOI18N
entryLine);
}
}
/**
* Get the name of the associated file.
* @return the file name
*/
public String getName() {
return name;
}
/**
* Set the name.
* @param theName the filename to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the revision.
* @return the revision
*/
public String getRevision() {
return revision;
}
/**
* Set the revision.
* @param theVersion the revision to set
*/
public void setRevision(String revision) {
this.revision = revision;
}
/**
* Get the last modification time.
*
* @return date.getTime() compatible with File.lastModified()
*/
public Date getLastModified() {
return lastModified;
}
/**
* Get the conflict information.
* @return the conflict String
*/
public String getConflict() {
return conflict;
}
/**
* Set the conflict information.
* @param theConflict the conflict information
*/
public void setConflict(String conflict) {
this.conflict = conflict;
this.lastModified = null;
if (conflict == null
|| conflict.equals(DUMMY_TIMESTAMP)
|| conflict.equals(MERGE_TIMESTAMP)
|| conflict.equals(DUMMY_TIMESTAMP_NEW_ENTRY)) {
return;
}
String dateString = conflict;
// Look for the position of + which indicates a conflict
int conflictIndex = dateString.indexOf(HAD_CONFLICTS);
if (conflictIndex >= 0) {
// if the timestamp matches the file, there will be an = following
// the +
int timeMatchIndex = dateString.indexOf(TIMESTAMP_MATCHES_FILE);
conflictIndex = Math.max(conflictIndex, timeMatchIndex);
}
// At this point the conflict index tells us where the real conflict
// string starts
if (conflictIndex >= 0) {
dateString = dateString.substring(conflictIndex + 1);
}
// if we have nothing after the = then don't try to parse it
if (dateString.length() == 0) {
return;
}
try {
this.lastModified = getLastModifiedDateFormatter().parse(dateString);
}
catch (Exception ex) {
lastModified = null;
// System.err.println("[Entry] can't parse " + dateString); //NOI18N
}
}
/**
* Get the options information.
* @return the options details
*/
public String getOptions() {
return options;
}
/**
* Set the options information.
* @param theOptions the options
*/
public void setOptions(String options) {
this.options = options;
}
/**
* Get the sticky information.
* It's either a tag, a date or null.
*/
public String getStickyInformation() {
if (tag != null) {
return tag;
}
return getDateFormatted();
}
/**
* Get the sticky tag information.
* May return null if no tag information was present. If so, you should
* check for date information. Note that tag and date information cannot
* both be present.
* @return the tag, or null if none is present
*/
public String getTag() {
return tag;
}
/**
* Set the sticky tag information.
* Setting this will remove any date information that is set.
* @param theTag the tag information
*/
public void setTag(String tag) {
this.tag = tag;
date = null;
}
/**
* Get sticky date information.
* May return null if no date information is available. If so, you should
* check for tag informaton. Note that tag and date information cannot both
* be present.
* @return the date, or null if none is present
*/
public Date getDate() {
return date;
}
/**
* Gets the sticky date information as a string in the appropriate format.
* Returns null if there ain't a sticky date assigned.
*/
public String getDateFormatted() {
if (getDate() == null) {
return null;
}
SimpleDateFormat format = getStickyDateFormatter();
String dateFormatted = format.format(getDate());
return dateFormatted;
}
/**
* Set the sticky date information.
* Note that setting this will remove any tag information that is currently set.
* @param theDate the date to use.
*/
public void setDate(Date date) {
this.date = date;
tag = null;
}
/**
* Determines whether the entry has a date (as opposed to a tag).
* @return true if the entry has a date, false otherwise
*/
public boolean hasDate() {
return (date != null);
}
/**
* Determines whether the entry has a tag (as opposed to a date).
* @return true if the entry has a tag, false otherwise
*/
public boolean hasTag() {
return (tag != null);
}
/**
* Determines whether the file is a binary file.
*/
public boolean isBinary() {
return options != null
&& options.equals(BINARY_FILE);
}
/**
* Determine whether there is no user file of that name.
* @return true if there is no user file of that name
*/
public boolean isNoUserFile() {
return revision == null
|| revision.equals(NO_USER_FILE);
}
/**
* Determine whether there is a new user file of that name.
* @return true if there is a new user file with that name
*/
public boolean isNewUserFile() {
return revision != null
&& revision.startsWith(NEW_USER_FILE);
}
/**
* Determine whether the user file of that name is to be removed.
* @return true if the user file with this name is to be removed
*/
public boolean isUserFileToBeRemoved() {
return revision != null
&& revision.startsWith(REMOVE_USER_FILE);
}
/**
* Determines whether the entry is valid.
* A valid entry has at least a name.
*/
public boolean isValid() {
return getName() != null &&
getName().length() > 0;
}
/**
* Determine whether the entry refers to a directory.
*/
public boolean isDirectory() {
return directory;
}
/**
* Set whether the entry refers to a directory.
*/
public void setDirectory(boolean directory) {
this.directory = directory;
}
/**
* Determine whether there were any conflicts.
* @return true if there were conflicts, false otherwise
*/
public boolean hadConflicts() {
if (conflict != null) {
return conflict.indexOf(HAD_CONFLICTS) >= 0;
}
else {
return false;
}
}
/**
* Determine whether the timestamp matches the file.
* @return true if the timpestamp does match the file, false otherwise
*/
public boolean timestampMatchesFile() {
return (conflict.charAt(1) == TIMESTAMP_MATCHES_FILE);
}
/**
* Create a string representation of the entry line.
* Create the standard CVS 1.10 entry line format.
*
* Th eline format is suitable for writing into CVS/Entries file.
* Conflict one must be transformed before sending to wire
* {@link org.netbeans.lib.cvsclient.command.BasicCommand#sendEntryAndModifiedRequests}.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
if (directory) {
buf.append(DIRECTORY_PREFIX);
}
else {
buf.append('/');
}
// if name is null, then this is a totally empty entry, so append
// nothing further
if (name != null) {
buf.append(name);
buf.append('/');
if (revision != null) {
buf.append(revision);
}
buf.append('/');
if (conflict != null) {
buf.append(conflict);
}
buf.append('/');
if (options != null) {
buf.append(options);
}
buf.append('/');
// TODO: put in tag_or_date section!!!
// MK - Added. Based on assumption "There can be only one"
if (tag != null && date == null) {
if ("HEAD".equals(tag) == false) {
buf.append(TAG);
buf.append(getTag());
}
}
else if (tag == null && date != null) {
String dateString = getDateFormatted();
buf.append(DATE);
buf.append(dateString);
}
}
return buf.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/ 0000755 0001753 0000144 00000000000 11175434236 023463 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/BasicCommand.java 0000644 0001753 0000144 00000052042 11175406776 026661 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* A class that provides common functionality for many of the CVS command
* that send similar sequences of requests.
* @author Robert Greig
*/
public abstract class BasicCommand extends BuildableCommand {
/**
* The requests that are sent and processed.
*/
protected List requests = new LinkedList();
/**
* The client services that are provided to this command.
*/
protected ClientServices clientServices;
/**
* Whether to update recursively.
*/
private boolean recursive = true;
/**
* The files and/or directories to operate on.
*/
protected File[] files;
/**
* Gets the value of the recursive option.
* @return true if recursive, false if not
* @deprecated use isRecursive instead
*/
public boolean getRecursive() {
return recursive;
}
/**
* Gets the value of the recursive option.
* @return true if recursive, false if not
*/
public boolean isRecursive() {
return recursive;
}
/**
* Sets the value of the recursive option.
* @param recursive true if the command should recurse, false otherwise
*/
public void setRecursive(boolean recursive) {
this.recursive = recursive;
}
/**
* Set the files and/or directories on which to execute the command.
* The way these are processed is:
*
- Default action (i.e. not setting the files explicitly or
* setting them to
null
) is to use the directory in which
* the command was executed (see how directories are treated, below)
* - Files are handled how you would expect
* - For directories, all files within the directory are sent
* @param theFiles the files to operate on. May be null to indicate that the
* local directory specified in the client should be used. Full, absolute
* canonical pathnames must be supplied.
*/
public void setFiles(File[] theFiles) {
// sort array.. files first, directories follow
if (theFiles == null) {
files = theFiles;
return;
}
// assert theFiles.length > 0 : "Empty array causes random AIOOBEs!"; // ClientRuntime.java:119
files = new File[theFiles.length];
int fileCount = 0;
int dirCount = 0;
int totalCount = theFiles.length;
for (int index = 0; index < totalCount; index++) {
File currentFile = theFiles[index];
if (currentFile.isDirectory()) {
files[totalCount - (1 + dirCount)] = currentFile;
dirCount = dirCount + 1;
}
else {
files[fileCount] = currentFile;
fileCount = fileCount + 1;
}
}
}
/**
* Get the files and/or directories specified for this command to operate
* on.
* @return the array of Files
*/
public File[] getFiles() {
return files;
}
/**
* Get a single file from the "files" list. returns only files, not directories.
* This method is used from within the builders, because for single file requests, the
* cvs server doesn't return us enough information to identify what file has been returned.
* Thus we sort the "files" array (files come before directories. Then the response froms erver comes in the same order
* and the files can be found this way.
*
* @param index the index of the file in the list.
*/
public File getXthFile(int index) {
if (index < 0 || index >= files.length) {
return null;
}
File file = files[index];
if (!file.isFile()) {
return null;
}
return file;
}
/**
* @param ending - the ending part of the file's pathname.. path separator is cvs's default '/'
*/
public File getFileEndingWith(String ending) {
String locEnding = ending.replace('\\', '/');
String localDir = getLocalDirectory().replace('\\','/');
int index = 0;
for (index = 0; index < files.length; index++) {
String path = files[index].getAbsolutePath();
String parentPath = files[index].getParentFile().getAbsolutePath().replace('\\', '/');
path = path.replace('\\', '/');
if ((path.endsWith(locEnding) && locEnding.indexOf('/') >= 0) ||
(files[index].getName().equals(locEnding) && parentPath.equals(localDir))) {
return files[index];
}
}
return null;
}
/**
* Add the appropriate requests for a specified path. For a directory,
* process all the files within that directory and for a single file,
* just send it. For each directory, send a directory request. For each
* file send an Entry request followed by a Modified request.
* @param path the particular path to issue requests for. May be
* either a file or a directory.
*/
private void addRequests(File path)
throws FileNotFoundException, IOException, CommandAbortedException {
if (path == null) {
throw new IllegalArgumentException("Cannot add requests for a " +
"null path.");
}
if (!path.exists() || path.isFile()) {
addRequestsForFile(path);
}
else {
addRequestsForDirectory(path);
}
}
/**
* Should return true if unchanged files should not be sent to server.
* If false is returned, all files will be sent to server
* This method is used by sendEntryAndModifiedRequests
.
*/
protected boolean doesCheckFileTime() {
return true;
}
/**
* Send an Entry followed by a Modified or Unchanged request based on
* whether the file has been untouched on the local machine.
*
* @param entry the entry for the file
* @param file the file in question
*/
protected void sendEntryAndModifiedRequests(Entry entry,
File file) {
if (entry == null) {
return;
}
// for deleted added files, don't send anything..
if (file != null && !file.exists() && entry.isNewUserFile()) {
return;
}
Date entryLastModified = entry.getLastModified();
boolean hadConflicts = entry.hadConflicts();
if (!hadConflicts) {
// we null out the conflict field if there is no conflict
// because we use that field to store the timestamp of the
// file (just like command-line CVS). There is no point
// in sending this information to the CVS server, even
// though it should be ignored by the server.
entry.setConflict(null);
} else if (fileRequiresConflictResolution(file, entry)) {
// send entry in wire conflict format
Entry clone = new Entry(entry.toString());
clone.setConflict(Entry.HAD_CONFLICTS_AND_TIMESTAMP_MATCHES_FILE);
entry = clone;
}
addRequest(new EntryRequest(entry));
if (file == null || !file.exists() || entry.isUserFileToBeRemoved()) {
return;
}
if (doesCheckFileTime() && !hadConflicts && entryLastModified != null) {
if (DateComparator.getInstance().equals(file.lastModified(),
entryLastModified.getTime())) {
addRequest(new UnchangedRequest(file.getName()));
return;
}
}
addRequest(new ModifiedRequest(file, entry.isBinary()));
}
/**
* When committing, we need to perform a check that will prevent the
* unmodified conflicting files from being checked in. This is the behavior
* of command line CVS client. This method checks the Entry for the file
* against the time stamp. The user can optimally call this method only if
* the Entry for the file indicates a conflict
* @param entry The Entry object corresponding to the file
* @param file The File object representing the file on the filesystem
* @return boolean Returns true if the file's timestamp is same or less than
* the time when the conflicting merge was done by CVS update as indicated
* by the Entry.
*/
private final boolean fileRequiresConflictResolution(File file, Entry entry) {
if (file == null) return false; // null file is set by clean copy
boolean ret = false;
if (entry.hadConflicts()) {
// TODO introduce common timestamp comparation logic
// We only test accuracy of upto a second (1000ms) because that is
// the precision of the timestamp in the entries file
long mergedTime = entry.getLastModified().getTime() / 1000;
long timeStampOfFile = file.lastModified() / 1000;
ret = timeStampOfFile <= mergedTime;
}
return ret;
}
/**
* Adds the appropriate requests for a given directory. Sends a
* directory request followed by as many Entry and Modified requests
* as required
* @param directory the directory to send requests for
* @throws IOException if an error occurs constructing the requests
*/
protected void addRequestsForDirectory(File directory)
throws IOException, CommandAbortedException {
if (!clientServices.exists(directory)) {
return;
}
if (clientServices.isAborted()) {
throw new CommandAbortedException("Command aborted during request generation", "Command aborted during request generation");
}
addDirectoryRequest(directory);
File [] dirFiles = directory.listFiles();
List localFiles;
if (dirFiles == null) {
localFiles = new ArrayList(0);
} else {
localFiles = new ArrayList(Arrays.asList(dirFiles));
localFiles.remove(new File(directory, "CVS"));
}
List subDirectories = null;
if (isRecursive()) {
subDirectories = new LinkedList();
}
// get all the entries we know about, and process them
for (Iterator it = clientServices.getEntries(directory); it.hasNext();) {
final Entry entry = (Entry)it.next();
final File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
if (isRecursive()) {
subDirectories.add(new File(directory, entry.getName()));
}
}
else {
addRequestForFile(file, entry);
}
localFiles.remove(file);
}
// In case that CVS folder does not exist, we need to process all
// directories that have CVS subfolders:
if (isRecursive() && !new File(directory, "CVS").exists()) {
File[] subFiles = directory.listFiles();
if (subFiles != null) {
for (int i = 0; i < subFiles.length; i++) {
if (subFiles[i].isDirectory() && new File(subFiles[i], "CVS").exists()) {
subDirectories.add(subFiles[i]);
}
}
}
}
for (Iterator it = localFiles.iterator(); it.hasNext();) {
String localFileName = ((File)it.next()).getName();
if (!clientServices.shouldBeIgnored(directory, localFileName)) {
addRequest(new QuestionableRequest(localFileName));
}
}
if (isRecursive()) {
for (Iterator it = subDirectories.iterator(); it.hasNext();) {
File subdirectory = (File)it.next();
File cvsSubDir = new File(subdirectory, "CVS"); //NOI18N
if (clientServices.exists(cvsSubDir)) {
addRequestsForDirectory(subdirectory);
}
}
}
}
/**
* This method is called for each explicit file and for files within a
* directory.
*/
protected void addRequestForFile(File file, Entry entry) {
sendEntryAndModifiedRequests(entry, file);
}
/**
* Add the appropriate requests for a single file. A directory request
* is sent, followed by an Entry and Modified request
* @param file the file to send requests for
* @throws IOException if an error occurs constructing the requests
*/
protected void addRequestsForFile(File file) throws IOException {
addDirectoryRequest(file.getParentFile());
try {
final Entry entry = clientServices.getEntry(file);
// a non-null entry means the file does exist in the
// Entries file for this directory
if (entry != null) {
addRequestForFile(file, entry);
} else if (file.exists()) {
// #50963 file exists locally without an entry AND the request is
// for the file explicitly
boolean unusedBinaryFlag = false;
addRequest(new ModifiedRequest(file, unusedBinaryFlag));
}
}
catch (IOException ex) {
System.err.println("An error occurred getting the Entry " +
"for file " + file + ": " + ex);
ex.printStackTrace();
}
}
/**
* Adds a DirectoryRequest (and maybe a StickyRequest) to the request list.
*/
protected final void addDirectoryRequest(File directory) {
// remove localPath prefix from directory. If left with
// nothing, use dot (".") in the directory request
String dir = getRelativeToLocalPathInUnixStyle(directory);
try {
String repository = clientServices.getRepositoryForDirectory(
directory.getAbsolutePath());
addRequest(new DirectoryRequest(dir, repository));
String tag = clientServices.getStickyTagForDirectory(directory);
if (tag != null) {
addRequest(new StickyRequest(tag));
}
}
catch (FileNotFoundException ex) {
// we can ignore this exception safely because it just means
// that the user has deleted a directory referenced in a
// CVS/Entries file
}
catch (IOException ex) {
System.err.println("An error occurred reading the respository " +
"for the directory " + dir + ": " + ex);
ex.printStackTrace();
}
}
/**
* Add the argument requests. The argument requests are created using
* the original set of files/directories passed in. Subclasses of this
* class should call this method at the appropriate point in their
* execute() method. Note that arguments are appended to the list.
*/
protected void addArgumentRequests() {
if (files == null) {
return;
}
for (int i = 0; i < files.length; i++) {
final File file = files[i];
String relativePath = getRelativeToLocalPathInUnixStyle(file);
addRequest(new ArgumentRequest(relativePath, true));
}
}
/**
* Execute a command. This implementation sends a Root request, followed
* by as many Directory and Entry requests as is required by the recurse
* setting and the file arguments that have been set. Subclasses should
* call this first, and tag on the end of the requests list any further
* requests and, finally, the actually request that does the command (e.g.
* update
, status
etc.)
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
* @throws CommandException if an error occurs executing the command
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
requests.clear();
clientServices = client;
super.execute(client, em);
if (client.isFirstCommand()) {
addRequest(new RootRequest(client.getRepository()));
}
addFileRequests();
}
private void addFileRequests() throws CommandException {
try {
if (files != null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
addRequests(files[i]);
}
}
else {
// if no arguments have been specified, then specify the
// local directory - the "top level" for this command
if (assumeLocalPathWhenUnspecified()) {
addRequests(new File(getLocalDirectory()));
}
}
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
}
/**
* The result from this command is used only when the getFiles() returns null or empty array.
* in such a case and when this method returns true, it is assumed the localpath should be taken
* as the 'default' file for the building of requests.
* Generally assumed to be true. Can be overriden by subclasses. However make sure you know what you are doing. :)
*/
protected boolean assumeLocalPathWhenUnspecified() {
return true;
}
/**
* Adds the specified request to the request list.
*/
protected final void addRequest(Request request) {
requests.add(request);
}
/**
* Adds the request for the current working directory.
*/
protected final void addRequestForWorkingDirectory(ClientServices clientServices)
throws IOException {
addRequest(new DirectoryRequest(".", //NOI18N
clientServices.getRepositoryForDirectory(getLocalDirectory())));
}
/**
* If the specified value is true, add a ArgumentRequest for the specified
* argument.
*/
protected final void addArgumentRequest(boolean value, String argument) {
if (!value) {
return;
}
addRequest(new ArgumentRequest(argument));
}
/**
* Appends the file's names to the specified buffer.
*/
protected final void appendFileArguments(StringBuffer buffer) {
File[] files = getFiles();
if (files == null) {
return;
}
for (int index = 0; index < files.length; index++) {
if (index > 0) {
buffer.append(' ');
}
buffer.append(files[index].getName());
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/BinaryBuilder.java 0000644 0001753 0000144 00000005247 11175406776 027101 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
/**
* Extended Builder interface. If implemented it's means
* that farmework must call this interface {@link #parseBytes}
* instead of {@link Builder#parseLine}.
*
* @author Petr Kuzel
*/
public interface BinaryBuilder {
/**
* Raw binary data from stream. One Mbinary
* is typicaly splitted into several chunks.
*
* @param chunk one data chunk. It must be cloned
* if builer wants to retain data after finishing
* this callback.
* @param len defines valid data length
*/
void parseBytes(byte[] chunk, int len);
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/BuildableCommand.java 0000644 0001753 0000144 00000016005 11175406776 027522 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import java.io.UnsupportedEncodingException;
/**
* A class that provides common functionality for many of the CVS command
* that send similar sequences of requests.
* @author Robert Greig
*/
public abstract class BuildableCommand extends Command {
/**
* An implementation of Builder interface that constructs a FileContainerInfo object from
* the server's output..
*/
protected Builder builder;
private final StringBuffer taggedLineBuffer = new StringBuffer();
/**
* A boolean value indicating if the user has used the setBuilder() method.
*/
private boolean builderSet;
/**
* Execute a command. This implementation sends a Root request, followed
* by as many Directory and Entry requests as is required by the recurse
* setting and the file arguments that have been set. Subclasses should
* call this first, and tag on the end of the requests list any further
* requests and, finally, the actually request that does the command (e.g.
* update
, status
etc.)
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
* @throws CommandException if an error occurs executing the command
*/
public void execute(ClientServices client, EventManager eventManager)
throws CommandException, AuthenticationException {
super.execute(client, eventManager);
if (builder == null && !isBuilderSet()) {
builder = createBuilder(eventManager);
}
}
/**
* Method that is called while the command is being executed.
* Descendants can override this method to return a Builder instance
* that will parse the server's output and create data structures.
*/
public Builder createBuilder(EventManager eventManager) {
return null;
}
public void messageSent(BinaryMessageEvent e) {
super.messageSent(e);
if (builder == null) {
return;
}
if (builder instanceof BinaryBuilder) { // XXX assert it?
BinaryBuilder binaryBuilder = (BinaryBuilder) builder;
binaryBuilder.parseBytes(e.getMessage(), e.getMessageLength());
}
}
public void messageSent(MessageEvent e) {
super.messageSent(e);
if (builder == null) {
return;
}
if (e instanceof EnhancedMessageEvent) {
EnhancedMessageEvent eEvent = (EnhancedMessageEvent)e;
builder.parseEnhancedMessage(eEvent.getKey(), eEvent.getValue());
return;
}
if (e.isTagged()) {
String message = MessageEvent.parseTaggedMessage(taggedLineBuffer, e.getMessage());
if (message != null) {
builder.parseLine(message, false);
taggedLineBuffer.setLength(0);
}
}
else {
if (taggedLineBuffer.length() > 0) {
builder.parseLine(taggedLineBuffer.toString(), false);
taggedLineBuffer.setLength(0);
}
//#67337 do not interpret piped data using platform default encoding
// UTF-8 causes problems as raw data (non UTf-8) can contain confusing sequences
// use safe encoding that does not interpret byte sequences
if (builder instanceof PipedFilesBuilder && e.isError() == false) {
try {
String iso88591 = new String(e.getRawData(), "ISO-8859-1");
builder.parseLine(iso88591, e.isError());
} catch (UnsupportedEncodingException e1) {
assert false;
}
} else {
builder.parseLine(e.getMessage(), e.isError());
}
}
}
/**
* Returns whether the builder is set.
*/
protected boolean isBuilderSet() {
return builderSet;
}
/**
* Used for setting user-defined builder.
* Can be also set null, in that case the builder mechanism is not used at
* all.
*/
public void setBuilder(Builder builder) {
this.builder = builder;
builderSet = true;
}
/**
* Called when server responses with "ok" or "error", (when the command finishes).
*/
public void commandTerminated(TerminationEvent e) {
if (builder == null) {
return;
}
if (taggedLineBuffer.length() > 0) {
builder.parseLine(taggedLineBuffer.toString(), false);
taggedLineBuffer.setLength(0);
}
builder.outputDone();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/Builder.java 0000644 0001753 0000144 00000004460 11175406776 025730 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
/**
* @author Milos Kleint
*/
public interface Builder {
void parseLine(String line, boolean isErrorMessage);
void parseEnhancedMessage(String key, Object value);
void outputDone();
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/Bundle.properties 0000644 0001753 0000144 00000006654 11175406776 027035 0 ustar ludo users # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
# Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
#
# The contents of this file are subject to the terms of either the GNU
# General Public License Version 2 only ("GPL") or the Common
# Development and Distribution License("CDDL") (collectively, the
# "License"). You may not use this file except in compliance with the
# License. You can obtain a copy of the License at
# http://www.netbeans.org/cddl-gplv2.html
# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
# specific language governing permissions and limitations under the
# License. When distributing the software, include this License Header
# Notice in each file and include the License file at
# nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the GPL Version 2 section of the License file that
# accompanied this code. If applicable, add the following below the
# License Header, with the fields enclosed by brackets [] replaced by
# your own identifying information:
# "Portions Copyrighted [year] [name of copyright owner]"
#
# Contributor(s):
#
# The Original Software is NetBeans. The Initial Developer of the Original
# Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
# Microsystems, Inc. All Rights Reserved.
#
# If you wish your version of this file to be governed by only the CDDL
# or only the GPL Version 2, indicate your decision by adding
# "[Contributor] elects to include this software in this distribution
# under the [CDDL or GPL Version 2] license." If you do not indicate a
# single choice of license, a recipient has the option to distribute
# your version of this file under either the CDDL, the GPL Version 2 or
# to extend the choice of license to its licensees as provided above.
# However, if you add GPL Version 2 code and therefore, elected the GPL
# Version 2 license, then the option applies only if the new code is
# made subject to such option by the copyright holder.
#--------------------------------------------------------------------
# ResourceBundle properties file
AddCommand.noFilesSpecified=No files have been specified for addition.
Client.commandAborted=Aborted during request processing.
Client.connectionAborted=Aborted during connecting to the server.
CommitCommand.logInfoFileNotExists=The file {0} that is used for commit log message doesn't exist.
CommitCommand.errorReadingLogFile=Error while reading file {0} that is used for commit log message.
CommandException.EndOfFile=Server closed connection. Check the output log for details.
ImportCommand.messageEmptry=The message may not be null nor empty!
ImportCommand.moduleEmpty=The module may not be null nor empty!
ImportCommand.moduleEmpty.text=
ImportCommand.releaseTagEmpty=The release tag may not be null nor empty!
ImportCommand.releaseTagEmpty.text=
ImportCommand.vendorTagEmpty=The vendor tag may not be null nor empty!
ImportCommand.vendorTagEmpty.text=
ExportCommand.moduleEmpty.text=
RemoveCommand.noFilesSpecified=No files have been specified for removal.
RemoveCommand.cannotDelete=Cannot delete file {0}.
WrapperUtils.clientDotWrapper.text=the .cvswrappers file in the home directory on the client
WrapperUtils.environmentWrapper.text=the environment variable CVSWRAPPERS
WrapperUtils.wrapperError.text=An error occurred while processing wrapper information from {0}.
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/Command.java 0000644 0001753 0000144 00000023041 11175406776 025714 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* All commands must extend this class. A command is essentially a
* collection of requests that make up what is logically known as a CVS
* command (from a user's perspective). Commands correspond to operations the
* user can perform with CVS, for example checkout a module or perform a
* diff on two file versions.
* Commands are automatically added as CVS event listeners. They can act
* on particular events and perhaps fire new events.
*
* @author Robert Greig
*/
public abstract class Command
implements CVSListener, Cloneable {
/**
* The local directory from which the command is being run.
* This gives us the ability to construct a full pathname for the file
* which we are processing. The information from the responses alone is
* not enough.
*/
protected String localDirectory;
/**
* The global options.
*/
private GlobalOptions globalOptions;
private boolean failed = false;
private String displayName;
/**
* Execute this command.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests
* @param e the event manager. The command can use this to fire events
* if necessary - for example, while parsing status responses.
* @return Whether the execution was successfull
*/
public void execute(ClientServices client, EventManager eventManager)
throws CommandException, CommandAbortedException, AuthenticationException {
setLocalDirectory(client.getLocalPath());
this.globalOptions = client.getGlobalOptions();
}
/**
* This method returns how the command would looklike when typed on the
* command line.
*
* Each command is responsible for constructing this information.
*
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*/
public abstract String getCVSCommand();
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name.
*/
public abstract String getCVSArguments();
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file).
*
* @return true if the option (switch) was recognized and set
*/
public abstract boolean setCVSCommand(char opt, String optArg);
/**
* Resets all switches in the command to the default behaviour.
* After calling this method, the command should behave defaultly.
*/
public abstract void resetCVSCommand();
/**
* Returns a String that defines which options are available for this
* particular command.
*/
public abstract String getOptString();
/**
* This method just calls the Object.clone() and makes it public.
*/
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException ex) {
return null;
}
}
public boolean hasFailed() {
return failed;
}
/**
* Called when the server wants to send a message to be displayed to
* the user. The message is only for information purposes and clients
* can choose to ignore these messages if they wish.
* @param e the event
*/
public void messageSent(MessageEvent e) {
if (e.isError() && (e.getSource() instanceof org.netbeans.lib.cvsclient.response.ErrorResponse)
|| e.getSource() == this) {
// We need to ignore ErrorMessageResponse
failed = true;
}
}
public void messageSent(BinaryMessageEvent e) {
}
/**
* Called when a file has been added.
* @param e the event
*/
public void fileAdded(FileAddedEvent e) {
}
/**
* Called when a file is going to be removed.
* @param e the event
*/
public void fileToRemove(FileToRemoveEvent e) {
}
/**
* Called when a file is removed.
* @param e the event
*/
public void fileRemoved(FileRemovedEvent e) {
}
/**
* Called when a file has been updated.
* @param e the event
*/
public void fileUpdated(FileUpdatedEvent e) {
}
/**
* Called when file status information has been received.
*/
public void fileInfoGenerated(FileInfoEvent e) {
}
/**
* Called when server responses with "ok" or "error", (when the command finishes).
*/
public void commandTerminated(TerminationEvent e) {
}
/**
* This is called when the servers has responded to an expand-modules
* request.
*/
public void moduleExpanded(ModuleExpansionEvent e) {
}
/**
* Returns the local path the command is associated with.
*/
public final String getLocalDirectory() {
return localDirectory;
}
/**
* Returns the local path the command is associated with.
* @deprecated Please use the getLocalDirectory() method instead.
*/
public final String getLocalPath() {
return localDirectory;
}
/**
* Get the global options.
*/
public final GlobalOptions getGlobalOptions() {
return globalOptions;
}
/**
* Returns the relative path of the specified file (relative to the set
* local path).
* Backward slashes will be replaced by forward slashes.
*/
public final String getRelativeToLocalPathInUnixStyle(File file) {
String filePath = file.getAbsolutePath();
int startIndex = localDirectory.length() + 1;
if (startIndex >= filePath.length()) {
return "."; //NOI18N
}
String relativePath = filePath.substring(startIndex);
return relativePath.replace('\\', '/');
}
/**
* Sets the local directory for the command.
*/
protected final void setLocalDirectory(String localDirectory) {
this.localDirectory = localDirectory;
}
/**
* Returns the trimmed version of the specified String s.
* The returned String is null if the specified String is null or contains
* only white spaces.
*/
protected static final String getTrimmedString(String s) {
if (s == null) {
return null;
}
s = s.trim();
if (s.length() == 0) {
return null;
}
return s;
}
/**
* Defines prefered display name or null
.
* Localized string should highlight command purpose (use verb in gerund).
* E.g. UpdateCommand
used to refresh statuses should
* be named "Refreshing Status" rather than "cvs -N update",
* "Updating" or "Status Refresh".
*/
public void setDisplayName(String name) {
this.displayName = name;
}
/**
* Returns localized name describing command purpose
* or null
.
*
* @see #getCVSCommand()
*/
public String getDisplayName() {
return displayName;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/CommandAbortedException.java 0000644 0001753 0000144 00000005223 11175406776 031076 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command;
/**
* This exception is thrown when a command is aborted during execution
* @author Robert Greig
*/
public class CommandAbortedException extends CommandException {
/**
* Creates new CommandAbortedException.
*/
public CommandAbortedException(String message, String localizedMessage) {
super(message, localizedMessage);
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/CommandException.java 0000644 0001753 0000144 00000011770 11175406776 027601 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
import java.text.*;
import java.util.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* This exception is thrown when an error occurs while executing a command.
* It is nearly always a container for another exception.
* @author Robert Greig
*/
public class CommandException extends Exception {
private Exception underlyingException;
private String localizedMessage;
private String message;
public CommandException(Exception underlyingException, String localizedMessage) {
this.underlyingException = underlyingException;
this.localizedMessage = localizedMessage;
}
public CommandException(String message, String localizedMessage) {
super(message);
this.message = message;
this.localizedMessage = localizedMessage;
}
public Exception getUnderlyingException() {
return underlyingException;
}
public void printStackTrace() {
if (underlyingException != null) {
underlyingException.printStackTrace();
}
else {
super.printStackTrace();
}
}
public void printStackTrace(PrintStream stream) {
if (underlyingException != null) {
underlyingException.printStackTrace(stream);
}
else {
super.printStackTrace(stream);
}
}
public void printStackTrace(PrintWriter writer) {
if (underlyingException != null) {
underlyingException.printStackTrace(writer);
}
else {
super.printStackTrace(writer);
}
}
public String getLocalizedMessage() {
if (localizedMessage == null) {
return message;
}
return localizedMessage;
}
public String getMessage() {
if (message == null) {
return localizedMessage;
}
return message;
}
protected static String getBundleString(String key) {
String value = null;
try {
ResourceBundle bundle = BundleUtilities.getResourceBundle(CommandException.class, "Bundle"); // NOI18N
if (bundle != null) {
value = bundle.getString(key);
}
}
catch (MissingResourceException exc) {
}
return value;
}
public static String getLocalMessage(String key) {
return getLocalMessage(key, null);
}
public static String getLocalMessage(String key, Object[] arguments) {
String locMessage = CommandException.getBundleString(key);
if (locMessage == null) {
return null;
}
if (arguments != null) {
locMessage = MessageFormat.format(locMessage, arguments);
}
return locMessage;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/CommandUtils.java 0000644 0001753 0000144 00000007114 11175406776 026740 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Thomas Singer.
* Portions created by Robert Greig are Copyright (C) 2001.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Thomas Singer.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command;
import java.util.*;
/**
* @author Thomas Singer
*/
public class CommandUtils {
/**
* Returns the directory relative to local path from the specified message.
* This method returns null, if the specified message isn't a EXAM_DIR-
* message.
*/
public static String getExaminedDirectory(String message, String examDirPattern) {
final int index = message.indexOf(examDirPattern);
final int startIndex = index + examDirPattern.length() + 1;
if (index < 0 || message.length() < startIndex + 1) {
return null;
}
return message.substring(startIndex);
}
/**
* for a list of string will return the string that equals the name parameter.
* To be used everywhere you need to have only one string occupying teh memory space,
* eg. in Builders to have the revision number strings not repeatedly in memory.
*/
public static String findUniqueString(String name, List list) {
if (name == null) {
return null;
}
int index = list.indexOf(name);
if (index >= 0) {
return (String)list.get(index);
}
else {
String newName = new String(name);
list.add(newName);
return newName;
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/DefaultFileInfoContainer.java 0000644 0001753 0000144 00000007746 11175406776 031217 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
/**
* Describes checkout/tag/update information for a file.
* The fields in instances of this object are populated by response handlers.
*
* @author Thomas Singer
*/
public class DefaultFileInfoContainer extends FileInfoContainer {
public static final String PERTINENT_STATE = "Y"; //NOI18N
public static final String MERGED_FILE = "G"; //NOI18N
private File file;
private String type;
public DefaultFileInfoContainer() {
}
/**
* Returns the associated file.
*/
public File getFile() {
return file;
}
/**
* Returns true if the associated file is a directory.
*/
public boolean isDirectory() {
File file = getFile();
if (file == null) {
return false;
}
return file.isDirectory();
}
/**
* Sets the associated file.
*/
public void setFile(File file) {
this.file = file;
}
/**
* Returns the type.
* Mostly the type value equals to the states returned by update and tag command.
* see description in cvs manual.
* Some states are added:
* G - file was merged (when using the cvs update -j command.
* D - file was deleted - no longer pertinent.
*/
public String getType() {
return type;
}
/**
* Sets the type.
*/
public void setType(String type) {
this.type = type;
}
/**
* Return a string representation of this object. Useful for debugging.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(type);
buffer.append(" "); //NOI18N
if (isDirectory()) {
buffer.append("Directory "); //NOI18N
}
buffer.append(file != null ? file.getAbsolutePath()
: "null"); //NOI18N
return buffer.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/FileInfoContainer.java 0000644 0001753 0000144 00000004773 11175406776 027707 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
/**
* It's a base class for all containers that store information being processed
* during execution of cvs commands.
* Such info is then transmitted via the event mechanism (CVSEvent) to the
* appropriate UI classes that use this information to display it to the user.
*
* @author Milos Kleint
*/
public abstract class FileInfoContainer {
public abstract File getFile();
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/GlobalOptions.java 0000644 0001753 0000144 00000045137 11175406776 027124 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command;
import java.io.File;
import java.util.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* Provides access to global options for a specific command.
* These are options traditionally set in the command line CVS tool before the
* command name, for example in the command:
* cvs -n update -dP
* -n is a global options but -dP are options specific to the update command.
*
*
Note that you can have different global options for each command you
* execute (just like command-line CVS).
*
* @author Robert Greig
*/
public class GlobalOptions implements Cloneable {
private List variables;
/**
* Determines whether no changes should be done to the local files.
* This is useful to request files, that would be updated.
*/
private boolean doNoChanges;
/**
* Whether to make checked out files read only (read/write is the default).
*/
private boolean checkedOutFilesReadOnly;
/**
* The CVS root to use.
*/
private String cvsRoot;
/**
* Whether to use Gzip-compression.
*/
private boolean useGzip = true;
/**
* The gzip compression level.
*/
private int compressionLevel = 0;
/**
* Supresses logging of the command in CVSROOT/history in the repository.
*/
private boolean noHistoryLogging;
/**
* The cvs gets more quiet than without this switch.
* However it still prints the important stuff.
* Note: If this switch is used, the Builder stuff and parsing of the output
* might break.
*/
private boolean moderatelyQuiet;
/**
* Is even more quiet.
* Commands which primary function is to send info, still do print something
* (diff, etc.), however other command are completely quiet.
* Note: If this switch is used, the Builder stuff and parsing of the output
* will break.
*/
private boolean veryQuiet;
/**
* Traces the execution of the command. Useful for tracing down what is
* causing problems.
* Note: If this switch is used, the Builder stuff and parsing of the output
* might break.
*/
private boolean traceExecution;
/**
* Whether a help information should be displayed - usage of the command.
*/
private boolean showHelp;
/**
* Whether a version information should be displayed.
*/
private boolean showVersion;
/**
* Whether to use ~/.cvsrc file or ignore it.
*/
private boolean ignoreCvsrc;
/**
* The directory that is used for temporary files.
*/
private File tempDir;
/**
* The editor, that is used to edit the commit message.
*/
private String editor;
/**
* Explicitly lists files/folders that must be left intact by the command.
*/
private File[] exclusions;
public GlobalOptions() {
variables = new ArrayList();
}
/**
* Sets list of non-modifiable files/folders. The client will effectively ignore all server responses
* that concern these files/folders or files beneath them.
*
* @param exclusions array of non-modifiable files/folders
*/
public void setExclusions(File[] exclusions) {
this.exclusions = exclusions;
}
/**
* Returns list of non-modifiable files/folders. The client effectively ignores all server responses
* that concern these files/folders or files beneath them.
*
* @return File [] list of files/folders that must be left intact by the command.
*/
public File[] getExclusions() {
return exclusions;
}
/**
* Tests whether the file is not modifiable as set by {@link #setExclusions(java.io.File[])}.
*
* @param file file to test
* @return true if the file must not be modified on disk, false otherwise
*/
public boolean isExcluded(File file) {
if (exclusions != null) {
for (int i = 0; i < exclusions.length; i++) {
if (isParentOrEqual(exclusions[i], file)) return true;
}
}
return false;
}
/**
* Tests parent/child relationship of files.
*
* @param parent file to be parent of the second parameter
* @param file file to be a child of the first parameter
* @return true if the second parameter represents the same file as the first parameter OR is its descendant (child)
*/
private static boolean isParentOrEqual(File parent, File file) {
for (; file != null; file = file.getParentFile()) {
if (file.equals(parent)) return true;
}
return false;
}
/**
* Creates a list of requests.
* Only those global options are included that can be sent to server (-q,
* -Q, -l, -t, -r, -n).
* To be added to the request list sent to the server.
*/
public List createRequestList() {
List requestList = new LinkedList();
if (variables.size() > 0) {
Iterator it = variables.iterator();
while (it.hasNext()) {
String keyValue = it.next().toString();
requestList.add(new SetRequest(keyValue));
}
}
if (isNoHistoryLogging()) {
requestList.add(new GlobalOptionRequest("-l")); //NOI18N
}
if (isDoNoChanges()) {
requestList.add(new GlobalOptionRequest("-n")); //NOI18N
}
if (isModeratelyQuiet()) {
requestList.add(new GlobalOptionRequest("-q")); //NOI18N
}
if (isVeryQuiet()) {
requestList.add(new GlobalOptionRequest("-Q")); //NOI18N
}
if (isTraceExecution()) {
requestList.add(new GlobalOptionRequest("-t")); //NOI18N
}
return requestList;
}
/**
* Returns a String that defines which options are available for global
* options.
*/
public String getOptString() {
return "Hvnfd:lqQtrws:z:T:e:"; //NOI18N
}
/**
* EQUALS to Command.setCVSCommand()
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'n') {
setDoNoChanges(true);
}
else if (opt == 'd') {
setCVSRoot(optArg);
}
else if (opt == 'l') {
setNoHistoryLogging(true);
}
else if (opt == 'q') {
setModeratelyQuiet(true);
}
else if (opt == 'Q') {
setVeryQuiet(true);
}
else if (opt == 't') {
setTraceExecution(true);
}
else if (opt == 't') {
setTraceExecution(true);
}
else if (opt == 'r') {
setCheckedOutFilesReadOnly(true);
}
else if (opt == 'w') {
setCheckedOutFilesReadOnly(false);
}
else if (opt == 's') {
setCvsVariable(optArg);
}
else if (opt == 'z') {
try {
setCompressionLevel(Integer.parseInt(optArg));
} catch (NumberFormatException nfex) {
}
}
else if (opt == 'H') {
setShowHelp(true);
}
else if (opt == 'v') {
setShowVersion(true);
}
else if (opt == 'f') {
setIgnoreCvsrc(true);
}
else if (opt == 'T') {
setTempDir(new File(optArg));
}
else if (opt == 'e') {
setEditor(optArg);
}
else {
return false;
}
return true;
}
/**
* Resets all switches in the command to the default behaviour.
* After calling this method, the command should behave defaultly.
* EQUALS to Command.resetCVSCommand()
*/
public void resetCVSCommand() {
setCheckedOutFilesReadOnly(false);
setDoNoChanges(false);
setModeratelyQuiet(false);
setNoHistoryLogging(false);
setTraceExecution(false);
setUseGzip(true);
setCompressionLevel(0);
setVeryQuiet(false);
setShowHelp(false);
setShowVersion(false);
setIgnoreCvsrc(false);
setTempDir(null);
setEditor(null);
setCVSRoot("");
clearCvsVariables();
}
/**
* Equals to the Command.getCVSCommand() functionality.
* Returns all the current switches in the command-line cvs style.
*/
public String getCVSCommand() {
StringBuffer switches = new StringBuffer();
if (isDoNoChanges()) {
switches.append("-n "); //NOI18N
}
if (isNoHistoryLogging()) {
switches.append("-l "); //NOI18N
}
if (isModeratelyQuiet()) {
switches.append("-q "); //NOI18N
}
if (isVeryQuiet()) {
switches.append("-Q "); //NOI18N
}
if (isTraceExecution()) {
switches.append("-t "); //NOI18N
}
if (isCheckedOutFilesReadOnly()) {
switches.append("-r "); //NOI18N
}
if (variables.size() > 0) {
Iterator it = variables.iterator();
while (it.hasNext()) {
String keyValue = it.next().toString();
switches.append("-s " + keyValue + " "); //NOI18N
}
}
if (compressionLevel != 0) {
switches.append("-z ");
switches.append(Integer.toString(compressionLevel));
switches.append(" ");
}
if (isIgnoreCvsrc()) {
switches.append("-f ");
}
if (tempDir != null) {
switches.append("-T ");
switches.append(tempDir.getAbsolutePath());
switches.append(" ");
}
if (editor != null) {
switches.append("-e ");
switches.append(editor);
switches.append(" ");
}
return switches.toString();
}
/**
* Adds one cvs internal enviroment variable.
* @param variable The format is NAME=VALUE.
*/
public void setCvsVariable(String variable) {
variables.add(variable);
}
/**
* Clears the list of cvs internal enviroment variables.
*/
public void clearCvsVariables() {
this.variables.clear();
}
/**
* Sets the cvs internal enviroment variables.
* It will clear any vrisables previously set.
* @param variables array of strings in format "KEY=VALUE".
*/
public void setCvsVariables(String[] variables) {
clearCvsVariables();
for (int i = 0; i < variables.length; i++) {
String variable = variables[i];
this.variables.add(variable);
}
}
public String[] getCvsVariables() {
String[] vars = new String[variables.size()];
vars = (String[])variables.toArray(vars);
return vars;
}
/**
* Sets whether no changes should be done to the files.
*/
public void setDoNoChanges(boolean doNoChanges) {
this.doNoChanges = doNoChanges;
}
/**
* Returns whether no changes should be done to the files.
*/
public boolean isDoNoChanges() {
return doNoChanges;
}
/**
* Are checked out files read only.
* @return the answer
*/
public boolean isCheckedOutFilesReadOnly() {
return checkedOutFilesReadOnly;
}
/**
* Set whether checked out files are read only. False is the default.
* @param readOnly true for readonly, false for read/write (default)
*/
public void setCheckedOutFilesReadOnly(boolean readOnly) {
checkedOutFilesReadOnly = readOnly;
}
/**
* Get the CVS root
* @return the CVS root value, e.g. :pserver:user@host@/usr/local/cvs
*/
public String getCVSRoot() {
return cvsRoot;
}
/**
* Set the CVS root
* @param cvsRoot CVS root to use
*/
public void setCVSRoot(String cvsRoot) {
this.cvsRoot = cvsRoot;
}
/**
* Set whether to use Gzip for file transmission/reception
* @param useGzip true if gzip should be used, false otherwise
*/
public void setUseGzip(boolean useGzip) {
this.useGzip = useGzip;
}
/**
* Get whether to use Gzip
* @return true if Gzip should be used, false otherwise
*/
public boolean isUseGzip() {
return useGzip;
}
/**
* Getter for property compressionLevel.
* @return Value of property compressionLevel.
*/
public int getCompressionLevel() {
return compressionLevel;
}
/**
* Setter for property compressionLevel.
* @param compressionLevel New value of property compressionLevel.
*/
public void setCompressionLevel(int compressionLevel) {
this.compressionLevel = compressionLevel;
}
/** Getter for property noHistoryLogging.
* @return Value of property noHistoryLogging.
*/
public boolean isNoHistoryLogging() {
return noHistoryLogging;
}
/** Setter for property noHistoryLogging.
* @param noHistoryLogging New value of property noHistoryLogging.
*/
public void setNoHistoryLogging(boolean noHistoryLogging) {
this.noHistoryLogging = noHistoryLogging;
}
/** Getter for property moderatelyQuiet.
* @return Value of property moderatelyQuiet.
*/
public boolean isModeratelyQuiet() {
return moderatelyQuiet;
}
/** Setter for property moderatelyQuiet.
* @param moderatelyQuiet New value of property moderatelyQuiet.
*/
public void setModeratelyQuiet(boolean moderatelyQuiet) {
this.moderatelyQuiet = moderatelyQuiet;
}
/** Getter for property veryQuiet.
* @return Value of property veryQuiet.
*/
public boolean isVeryQuiet() {
return veryQuiet;
}
/** Setter for property veryQuiet.
* @param veryQuiet New value of property veryQuiet.
*/
public void setVeryQuiet(boolean veryQuiet) {
this.veryQuiet = veryQuiet;
}
/** Getter for property traceExecution.
* @return Value of property traceExecution.
*/
public boolean isTraceExecution() {
return traceExecution;
}
/** Setter for property traceExecution.
* @param traceExecution New value of property traceExecution.
*/
public void setTraceExecution(boolean traceExecution) {
this.traceExecution = traceExecution;
}
/**
* Getter for property showHelp.
* @return Value of property showHelp.
*/
public boolean isShowHelp() {
return showHelp;
}
/**
* Setter for property showHelp.
* @param showHelp New value of property showHelp.
*/
public void setShowHelp(boolean showHelp) {
this.showHelp = showHelp;
}
/**
* Getter for property showVersion.
* @return Value of property showVersion.
*/
public boolean isShowVersion() {
return showVersion;
}
/**
* Setter for property showVersion.
* @param showVersion New value of property showVersion.
*/
public void setShowVersion(boolean showVersion) {
this.showVersion = showVersion;
}
/**
* Getter for property ignoreCvsrc.
* @return Value of property ignoreCvsrc.
*/
public boolean isIgnoreCvsrc() {
return ignoreCvsrc;
}
/**
* Setter for property ignoreCvsrc.
* @param ignoreCvsrc New value of property ignoreCvsrc.
*/
public void setIgnoreCvsrc(boolean ignoreCvsrc) {
this.ignoreCvsrc = ignoreCvsrc;
}
/**
* Getter for property tempDir.
* @return Value of property tempDir.
*/
public java.io.File getTempDir() {
return tempDir;
}
/**
* Setter for property tempDir.
* @param tempDir New value of property tempDir.
*/
public void setTempDir(java.io.File tempDir) {
this.tempDir = tempDir;
}
/**
* Getter for property editor.
* @return Value of property editor.
*/
public String getEditor() {
return editor;
}
/**
* Setter for property editor.
* @param editor New value of property editor.
*/
public void setEditor(String editor) {
this.editor = editor;
}
/**
* This method just calls the Object.clone() and makes it public.
*/
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException ex) {
// never can occur
return null;
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/KeywordSubstitutionOptions.java 0000644 0001753 0000144 00000007252 11175406776 032001 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
/**
* @author Thomas Singer
*/
public final class KeywordSubstitutionOptions {
public static final KeywordSubstitutionOptions DEFAULT = new KeywordSubstitutionOptions("kv"); //NOI18N
public static final KeywordSubstitutionOptions DEFAULT_LOCKER = new KeywordSubstitutionOptions("kvl"); //NOI18N
public static final KeywordSubstitutionOptions ONLY_KEYWORDS = new KeywordSubstitutionOptions("k"); //NOI18N
public static final KeywordSubstitutionOptions ONLY_VALUES = new KeywordSubstitutionOptions("v"); //NOI18N
public static final KeywordSubstitutionOptions OLD_VALUES = new KeywordSubstitutionOptions("o"); //NOI18N
public static final KeywordSubstitutionOptions BINARY = new KeywordSubstitutionOptions("b"); //NOI18N
public static KeywordSubstitutionOptions findKeywordSubstOption(String keyword) {
if (BINARY.toString().equals(keyword)) {
return BINARY;
}
if (DEFAULT.toString().equals(keyword)) {
return DEFAULT;
}
if (DEFAULT_LOCKER.toString().equals(keyword)) {
return DEFAULT_LOCKER;
}
if (OLD_VALUES.toString().equals(keyword)) {
return OLD_VALUES;
}
if (ONLY_KEYWORDS.toString().equals(keyword)) {
return ONLY_KEYWORDS;
}
if (ONLY_VALUES.toString().equals(keyword)) {
return ONLY_VALUES;
}
return null;
}
private String value;
private KeywordSubstitutionOptions(String value) {
this.value = value;
}
public String toString() {
return value;
}
} netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/PipedFileInformation.java 0000644 0001753 0000144 00000010557 11175406776 030415 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
/**
* Contains intercepted infomation from command standard output.
* Actula data are held in temporary file.
*
*/
public class PipedFileInformation extends FileInfoContainer {
private File file;
private String repositoryRevision;
private String repositoryFileName;
private File tempFile;
private OutputStream tmpStream;
public PipedFileInformation(File tempFile) {
this.tempFile = tempFile;
//this.tempFile.deleteOnExit();
try {
tmpStream = new BufferedOutputStream(new FileOutputStream(tempFile));
}
catch (IOException ex) {
// TODO
}
}
/**
* Returns the original file. For piped content see {@link #getTempFile()}.
*/
public File getFile() {
return file;
}
/**
* Sets the original file.
*/
protected void setFile(File file) {
this.file = file;
}
/**
* Returns the revision of the incoming file.
*/
public String getRepositoryRevision() {
return repositoryRevision;
}
/**
* Sets the revision of the incoming file.
*/
protected void setRepositoryRevision(String repositoryRevision) {
this.repositoryRevision = repositoryRevision;
}
/**
* Returns the filename in the repository.
*/
public String getRepositoryFileName() {
return repositoryFileName;
}
/**
* Sets the repository filename.
*/
protected void setRepositoryFileName(String repositoryFileName) {
this.repositoryFileName = repositoryFileName;
}
/**
* Adds the specified line to the temporary file.
*/
protected void addToTempFile(byte[] bytes) throws IOException {
if (tmpStream != null) {
tmpStream.write(bytes);
}
}
/**
* Adds the specified line to the temporary file.
*/
public void addToTempFile(byte[] bytes, int len) throws IOException {
if (tmpStream != null) {
tmpStream.write(bytes, 0, len);
}
}
protected void closeTempFile() throws IOException {
if (tmpStream != null) {
tmpStream.flush();
tmpStream.close();
}
}
public File getTempFile() {
return tempFile;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/PipedFilesBuilder.java 0000644 0001753 0000144 00000016340 11175406776 027675 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of "checkout with -p switch" information object and storing of
* the checked out file to the temporary file and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
*/
public class PipedFilesBuilder implements Builder, BinaryBuilder {
private static final String ERR_START = "======="; //NOI18N
private static final String ERR_CHECK = "Checking out "; //NOI18N
private static final String ERR_RCS = "RCS: "; //NOI18N
private static final String ERR_VERS = "VERS: "; //NOI18N
private static final String EXAM_DIR = ": Updating"; //NOI18N
private static final byte [] lineSeparator = System.getProperty("line.separator").getBytes();
/**
* The module object that is currently being built.
*/
private PipedFileInformation fileInformation;
/**
* The event manager to use.
*/
private EventManager eventManager;
/**
* The directory in which the file being processed lives.
* This is relative to the local directory.
*/
private String fileDirectory;
private BuildableCommand command;
private TemporaryFileCreator tempFileCreator;
/**
* Creates a new Builder for the PipeFileResponse.
*/
public PipedFilesBuilder(EventManager eventManager,
BuildableCommand command,
TemporaryFileCreator tempFileCreator) {
this.eventManager = eventManager;
this.command = command;
this.tempFileCreator = tempFileCreator;
}
public void outputDone() {
if (fileInformation == null) {
return;
}
try {
fileInformation.closeTempFile();
}
catch (IOException exc) {
//TODO
}
eventManager.fireCVSEvent(new FileInfoEvent(this, fileInformation));
fileInformation = null;
}
public void parseBytes(byte[] bytes, int len) {
if (fileInformation == null) {
// HOTFIX there is no header for :local: repositories (thereare two copies in this source)
// XXX it might be dangerous because PipedFileInformation stays partialy unitialized
try {
fileInformation = new PipedFileInformation(File.createTempFile("checkout", null));
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileInformation.addToTempFile(bytes, len);
}
catch (IOException exc) {
outputDone();
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (isErrorMessage) {
if (line.indexOf(EXAM_DIR) >= 0) {
fileDirectory = line.substring(line.indexOf(EXAM_DIR) + EXAM_DIR.length()).trim();
}
else if (line.startsWith(ERR_CHECK)) {
processFile(line);
}
else if (line.startsWith(ERR_RCS)) {
if (fileInformation != null) {
String repositoryName =
line.substring(ERR_RCS.length()).trim();
fileInformation.setRepositoryFileName(repositoryName);
}
}
else if (line.startsWith(ERR_VERS)) {
if (fileInformation != null) {
String repositoryRevision =
line.substring(ERR_RCS.length()).trim();
fileInformation.setRepositoryRevision(repositoryRevision);
}
}
// header stuff..
}
else {
if (fileInformation == null) {
// HOTFIX there is no header for :local: repositories (thereare two copies in this source)
// XXX it might be dangerous because PipedFileInformation stays partialy unitialized
try {
fileInformation = new PipedFileInformation(File.createTempFile("checkout", null));
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileInformation != null) {
try {
fileInformation.addToTempFile(line.getBytes("ISO-8859-1")); // see BuildableCommand
fileInformation.addToTempFile(lineSeparator);
}
catch (IOException exc) {
outputDone();
}
}
}
}
private void processFile(String line) {
outputDone();
String filename = line.substring(ERR_CHECK.length());
try {
File temporaryFile = tempFileCreator.createTempFile(filename);
fileInformation = new PipedFileInformation(temporaryFile);
}
catch (IOException ex) {
fileInformation = null;
return;
}
fileInformation.setFile(createFile(filename));
}
private File createFile(String fileName) {
File file = new File(command.getLocalDirectory(), fileName);
return file;
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/RepositoryCommand.java 0000644 0001753 0000144 00000020546 11175406776 030023 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* A class that provides common functionality for CVS commands that
* operate upon the repository.
*
* @author Martin Entlicher
*/
public abstract class RepositoryCommand extends BuildableCommand {
/**
* The requests that are sent and processed.
*/
protected List requests = new LinkedList();
/**
* The client services that are provided to this command.
*/
protected ClientServices clientServices;
/**
* Whether to process recursively.
*/
private boolean recursive = true;
/**
* The modules to process. These names are unexpanded and will be passed
* to a module-expansion request.
*/
protected final List modules = new LinkedList();
/**
* The expanded modules.
*/
protected final List expandedModules = new LinkedList();
/**
* Gets the value of the recursive option.
* @return true if recursive, false if not
*/
public boolean isRecursive() {
return recursive;
}
/**
* Sets the value of the recursive option.
* @param r true if the command should recurse, false otherwise
*/
public void setRecursive(boolean recursive) {
this.recursive = recursive;
}
/**
* Add a module to process.
* @param module the name of the module to process
*/
public void addModule(String module) {
modules.add(module);
}
/**
* Set the modules to process.
* @param modules the names of the modules to process
*/
public void setModules(String[] modules) {
clearModules();
if (modules == null) {
return;
}
for (int i = 0; i < modules.length; i++) {
String module = modules[i];
this.modules.add(module);
}
}
/**
* Get the array of modules that are set to be processed.
*/
public String[] getModules() {
String[] mods = new String[modules.size()];
mods = (String[])modules.toArray(mods);
return mods;
}
/**
* Clear the list of modules.
*/
public void clearModules() {
this.modules.clear();
}
/**
* Add the argument requests. The argument requests are created using
* the expanded set of modules passed in. Subclasses of this
* class should call this method at the appropriate point in their
* postExpansionExecute() method. Note that arguments are appended to the list.
*/
protected final void addArgumentRequests() {
if (expandedModules.size() == 0) {
return;
}
for (Iterator it = expandedModules.iterator(); it.hasNext(); ) {
final String module = (String) it.next();
addRequest(new ArgumentRequest(module));
}
}
/**
* This is called when the server has responded to an expand-modules
* request.
*/
public final void moduleExpanded(ModuleExpansionEvent e) {
expandedModules.add(e.getModule());
}
/**
* Execute this command. This method sends the ExpandModulesRequest in order
* to expand the modules that were set. The actual execution is performed by
* {@link #postExpansionExecute} method.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
public final void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
requests.clear();
super.execute(client, em);
clientServices = client;
if (client.isFirstCommand()) {
requests.add(new RootRequest(client.getRepository()));
}
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
requests.add(new ArgumentRequest(module));
}
expandedModules.clear();
requests.add(new DirectoryRequest(".", client.getRepository())); //NOI18N
requests.add(new ExpandModulesRequest());
try {
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
requests.clear();
postExpansionExecute(client, em);
}
/**
* Execute this command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
protected abstract void postExpansionExecute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException;
/**
* Adds the specified request to the request list.
*/
protected final void addRequest(Request request) {
requests.add(request);
}
/**
* Adds the request for the current working directory.
*/
protected final void addRequestForWorkingDirectory(ClientServices clientServices)
throws IOException {
addRequest(new DirectoryRequest(".", //NOI18N
clientServices.getRepositoryForDirectory(getLocalDirectory())));
}
/**
* If the specified value is true, add a ArgumentRequest for the specified
* argument.
*/
protected final void addArgumentRequest(boolean value, String argument) {
if (!value) {
return;
}
addRequest(new ArgumentRequest(argument));
}
/**
* Appends the file's names to the specified buffer.
*/
protected final void appendModuleArguments(StringBuffer buffer) {
if (expandedModules.size() == 0) {
return;
}
Iterator it = expandedModules.iterator();
buffer.append((String) it.next());
while (it.hasNext()) {
buffer.append(' ');
buffer.append((String) it.next());
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/TemporaryFileCreator.java 0000644 0001753 0000144 00000004402 11175406776 030440 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
import java.io.*;
/**
* @author Milos Kleint
*/
public interface TemporaryFileCreator {
File createTempFile(String filename) throws IOException;
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/Watch.java 0000644 0001753 0000144 00000007201 11175406776 025404 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
/**
* @author Thomas Singer
* @version Dec 2, 2001
*/
public class Watch {
public static final Watch EDIT = new Watch("edit", "E", // NOI18N
new String[]{"edit"}); // NOI18N
public static final Watch UNEDIT = new Watch("unedit", "U", // NOI18N
new String[]{"unedit"}); // NOI18N
public static final Watch COMMIT = new Watch("commit", "C", // NOI18N
new String[]{"commit"}); // NOI18N
public static final Watch ALL = new Watch("all", "EUC", // NOI18N
new String[]{"edit", "unedit", "commit"}); // NOI18N
public static final Watch NONE = new Watch("none", "", // NOI18N
new String[0]);
/**
* Returns the temporary watch value used in the Notify request.
*/
public static String getWatchString(Watch watch) {
if (watch == null) {
return NONE.getValue();
}
return watch.getValue();
}
private final String name;
private final String value;
private final String[] arguments;
private Watch(String name, String value, String[] arguments) {
this.name = name;
this.value = value;
this.arguments = arguments;
}
public String[] getArguments() {
return arguments;
}
public String toString() {
return name;
}
private String getValue() {
return value;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/add/ 0000755 0001753 0000144 00000000000 11175434236 024213 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/add/AddBuilder.java 0000644 0001753 0000144 00000020642 11175406776 027071 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.add;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of add information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
*/
public class AddBuilder implements Builder {
private static final String UNKNOWN = ": nothing known about"; //NOI18N
private static final String ADDED = " added to the repository"; //NOI18N
private static final String WARNING = ": warning: "; //NOI18N
private static final String ALREADY_ENTERED = " has already been entered"; //NOI18N
private static final String SCHEDULING = ": scheduling file `"; //NOI18N
private static final String USE_COMMIT = ": use 'cvs commit' "; //NOI18N
private static final String DIRECTORY = "Directory "; //NOI18N
private static final String READDING = ": re-adding file "; //NOI18N
private static final String RESURRECTED = ", resurrected"; //NOI18N
private static final String RESUR_VERSION = ", version "; //NOI18N
private static final boolean DEBUG = false;
/**
* The status object that is currently being built.
*/
private AddInformation addInformation;
/**
* The event manager to use.
*/
private EventManager eventManager;
/**
* The directory in which the file being processed lives.
* This is relative to the local directory
*/
private String fileDirectory;
private AddCommand addCommand;
private boolean readingTags;
public AddBuilder(EventManager eventManager, AddCommand addCommand) {
this.eventManager = eventManager;
this.addCommand = addCommand;
}
public void outputDone() {
if (addInformation != null) {
FileInfoEvent event = new FileInfoEvent(this, addInformation);
eventManager.fireCVSEvent(event);
addInformation = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (line.endsWith(ADDED)) {
String directory =
line.substring(DIRECTORY.length(), line.indexOf(ADDED));
addDirectory(directory);
}
else if (line.indexOf(SCHEDULING) >= 0) {
String filename =
line.substring(line.indexOf(SCHEDULING) + SCHEDULING.length(), line.indexOf('\'')).trim();
addFile(filename);
}
else if (line.indexOf(READDING) >= 0) {
String filename =
line.substring(line.indexOf(READDING) + READDING.length(), line.indexOf('(')).trim();
addFile(filename);
}
else if (line.endsWith(RESURRECTED)) {
String filename =
line.substring(0, line.length() - RESURRECTED.length());
resurrectFile(filename);
}
// ignore the rest..
}
private File createFile(String fileName) {
File locFile = addCommand.getFileEndingWith(fileName);
if (locFile == null) {
// in case the exact match was not achieved using the getFileEndingWith method
// let's try to find the best match possible.
// iterate from the back of the filename string and try to match the endings
// of getFiles(). the best match is picked then.
// Works ok for files and directories in add, should not probably be used
// elsewhere where it's possible to have recursive commands and where resulting files
// are not listed in getFiles()
String name = fileName.replace('\\', '/');
File[] files = addCommand.getFiles();
int maxLevel = name.length();
File bestMatch = null;
String[] paths = new String[files.length];
for (int index = 0; index < files.length; index++) {
paths[index] = files[index].getAbsolutePath().replace('\\', '/');
}
int start = name.lastIndexOf('/');
String part = null;
if (start < 0) {
part = name;
} else {
part = name.substring(start + 1);
}
while (start >= 0 || part != null) {
boolean wasMatch = false;
for (int index = 0; index < paths.length; index++) {
if (paths[index].endsWith(part)) {
bestMatch = files[index];
wasMatch = true;
}
}
start = name.lastIndexOf('/', start - 1);
if (start < 0 || !wasMatch) {
break;
}
part = name.substring(start + 1);
}
return bestMatch;
}
return locFile;
}
private void addDirectory(String name) {
addInformation = new AddInformation();
addInformation.setType(AddInformation.FILE_ADDED);
String dirName = name.replace('\\', '/');
/* int index = dirName.lastIndexOf('/');
if (index > 0) {
dirName = dirName.substring(index + 1, dirName.length());
}
*/
addInformation.setFile(createFile(dirName));
outputDone();
}
private void addFile(String name) {
addInformation = new AddInformation();
addInformation.setFile(createFile(name));
addInformation.setType(AddInformation.FILE_ADDED);
outputDone();
}
private void resurrectFile(String line) {
int versionIndex = line.lastIndexOf(RESUR_VERSION);
String version = line.substring(versionIndex + RESUR_VERSION.length()).trim();
String cutLine = line.substring(0, versionIndex).trim();
int fileIndex = cutLine.lastIndexOf(' ');
String name = cutLine.substring(fileIndex).trim();
if (DEBUG) {
System.out.println("line1=" + line); //NOI18N
System.out.println("versionIndex=" + versionIndex); //NOI18N
System.out.println("version=" + version); //NOI18N
System.out.println("fileindex=" + fileIndex); //NOI18N
System.out.println("filename=" + name); //NOI18N
}
addInformation = new AddInformation();
addInformation.setType(AddInformation.FILE_RESURRECTED);
addInformation.setFile(createFile(name));
outputDone();
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/add/AddCommand.java 0000644 0001753 0000144 00000062000 11175406776 027053 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.add;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.util.SimpleStringPattern;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* Adds a file or directory.
* @author Robert Greig
*/
public class AddCommand extends BuildableCommand {
/**
* Constants that identify a message that creates a directory in
* repository.
*/
private static final String DIR_ADDED = " added to the repository"; //NOI18N
private static final String DIRECTORY = "Directory "; //NOI18N
/**
* The requests that are sent and processed.
*/
private List requests;
/**
* The argument requests that are collected and sent in the end just before the
* add request.
*/
private final List argumentRequests = new LinkedList();
/**
* The list of new directories.
*/
/*
private HashMap newDirList;
*/
private final List newDirList = new LinkedList();
/**
* The client services that are provided to this command.
*/
private ClientServices clientServices;
/**
* The files and/or directories to operate on.
*/
private File[] files;
/**
* Holds value of property message, (add's switch -m).
*/
private String message;
/**
* Holds value of property keywordSubst.
*/
private KeywordSubstitutionOptions keywordSubst;
/**
*This is the merged wrapper map that contains has both server side
*and client side wrapper settings merged except for the .cvswrappers
*in the individual directories
*/
private Map wrapperMap;
/**
* Holds the cvswrappers map for each directory, keyed
* by directory name
*/
private HashMap dir2WrapperMap = new HashMap(16);
private static final Map EMPTYWRAPPER = new HashMap(1);
/**
* Constructor.
*/
public AddCommand() {
resetCVSCommand();
}
/**
* Set the files and/or directories on which to execute the command.
* Sorts the paameter so that directories are first and files follow.
* That way a directory and it's content will be passed correctly.
* The user of the library has to specify all the files+dirs being added though.
* This is just a sanity check, so that no unnessesary errors occur.
*/
public void setFiles(File[] files) {
this.files = files;
if (files == null) {
return;
}
// sort array: directories first, files follow
this.files = new File[files.length];
int dirCount = 0;
int fileCount = 0;
int totalCount = files.length;
for (int index = 0; index < totalCount; index++) {
File currentFile = files[index];
if (currentFile.isDirectory()) {
this.files[dirCount] = currentFile;
dirCount++;
}
else {
this.files[totalCount - (1 + fileCount)] = currentFile;
fileCount++;
}
}
}
/**
* Get the files and/or directories specified for this command to operate
* on.
* @return the array of Files
*/
public File[] getFiles() {
return files;
}
/**
* @param ending - the ending part of the file's pathname.. path separator is cvs's default '/'
*/
public File getFileEndingWith(String ending) {
String locEnding = ending.replace('\\', '/');
String localDir = getLocalDirectory().replace('\\','/');
int index = 0;
for (index = 0; index < files.length; index++) {
String path = files[index].getAbsolutePath();
String parentPath = files[index].getParentFile().getAbsolutePath().replace('\\', '/');
path = path.replace('\\', '/');
if ((path.endsWith(locEnding) && locEnding.indexOf('/') >= 0) ||
(files[index].getName().equals(locEnding) && parentPath.equals(localDir))) {
return files[index];
}
}
return null;
}
/**
* Getter for property message.
* @return Value of property message.
*/
public String getMessage() {
return message;
}
/**
* Setter for property message.
* @param message New value of property message.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Getter for property keywordSubst.
* @return Value of property keywordSubst.
*/
public KeywordSubstitutionOptions getKeywordSubst() {
return keywordSubst;
}
/**
* Setter for property keywordSubst.
* @param keywordSubst New value of property keywordSubst.
*/
public void setKeywordSubst(KeywordSubstitutionOptions keywordSubst) {
this.keywordSubst = keywordSubst;
}
/**
* Add requests for a particular file or directory to be added.
*/
protected void addRequests(File file)
throws IOException, CommandException {
if (file.isDirectory()) {
addRequestsForDirectory(file, false);
}
else {
addRequestsForFile(file);
}
}
/**
* Add requests for a particular directory.
* @param directory the directory to add
* @param adding - for the directory to be added, set to true.
* used internally to recurse Directory requests.
* @throws IOException if an error occurs
*/
private void addRequestsForDirectory(File directory, boolean recursion)
throws IOException {
File parentDirectory = directory.getParentFile();
String dir = recursion
? getRelativeToLocalPathInUnixStyle(directory)
: getRelativeToLocalPathInUnixStyle(parentDirectory);
String partPath;
if (dir.equals(".")) { //NOI18N
partPath = directory.getName();
}
else {
// trim the leading slash from the pathname we end up with
// (e.g. we end up with something like \banana\foo
// and this gives us banana\foo). Also replace backslashes with
// forward slashes. The standard CVS server doesn't like
// backslashes very much.
partPath = dir + "/" + directory.getName(); //NOI18N
// recursively scroll back to the localPath..
addRequestsForDirectory(parentDirectory, true);
}
if (recursion) {
partPath = dir;
}
// Note that the repository file for the directory being added has not
// been created yet, so we are forced to read the repository for
// the parent directory and build the appropriate entry by tagging
// on the directory name (called partPath here)
String repository;
String tag;
if (recursion) {
repository = clientServices.getRepositoryForDirectory(
directory.getAbsolutePath());
tag = clientServices.getStickyTagForDirectory(directory);
}
else {
repository = clientServices.getRepositoryForDirectory(
parentDirectory.getAbsolutePath());
if (repository.endsWith(".")) {
repository = repository.substring(0, repository.length() - 1) + directory.getName();
} else {
repository = repository + "/" + directory.getName(); //NOI18N
}
tag = clientServices.getStickyTagForDirectory(parentDirectory);
}
requests.add(new DirectoryRequest(partPath, repository));
if (tag != null) {
requests.add(new StickyRequest(tag));
}
if (!recursion) {
argumentRequests.add(new ArgumentRequest(partPath));
/*
newDirList.put(partPath, repository);
*/
newDirList.add(new Paths(partPath, repository));
}
// MK argument after Dir request.. also with the rel path from the current working dir
}
/**
* Add requests for a particular file.
*/
protected void addRequestsForFile(File file)
throws IOException, CommandException {
File directory = file.getParentFile();
String dir = getRelativeToLocalPathInUnixStyle(directory);
String repository = clientServices.getRepositoryForDirectory(
directory.getAbsolutePath());
requests.add(new DirectoryRequest(dir, repository));
String tag = clientServices.getStickyTagForDirectory(directory);
if (tag != null) {
requests.add(new StickyRequest(tag));
}
Entry entry = clientServices.getEntry(file);
if (entry != null) {
requests.add(new EntryRequest(entry));
}
else {
Map directoryLevelWrapper = (Map) dir2WrapperMap.get(dir);
if (directoryLevelWrapper == null) {
// we have not parsed the cvs wrappers for this directory
// read the wrappers for this directory
File wrapperFile = new File(directory, ".cvswrappers"); // NOI18N
if (wrapperFile.exists()) {
directoryLevelWrapper = new HashMap(5);
WrapperUtils.readWrappersFromFile(wrapperFile, directoryLevelWrapper);
}
else {
directoryLevelWrapper = EMPTYWRAPPER;
}
// store the wrapper map indexed by directory name
dir2WrapperMap.put(dir, directoryLevelWrapper);
}
boolean isBinary = isBinary(clientServices, file.getName(), directoryLevelWrapper);
if (isBinary) {
requests.add(new KoptRequest("-kb")); // NOI18N
}
requests.add(new IsModifiedRequest(file));
}
if (dir.equals(".")) { //NOI18N
argumentRequests.add(new ArgumentRequest(file.getName(), true));
}
else {
argumentRequests.add(new ArgumentRequest(dir + "/" + file.getName())); //NOI18N
}
}
/**
* Returns true, if the file for the specified filename should be treated as
* a binary file.
*
* The information comes from the wrapper map and the set keywordsubstitution.
*/
private boolean isBinary(ClientServices client, String filename, Map directoryLevelWrappers) throws CommandException {
KeywordSubstitutionOptions keywordSubstitutionOptions = getKeywordSubst();
if (keywordSubstitutionOptions == KeywordSubstitutionOptions.BINARY) {
return true;
}
// The keyWordSubstitutions was set based on MIME-types by
// CVSAdd which had no notion of cvswrappers. Therefore some
// filetypes returned as text may actually be binary within CVS
// We check for those files here
boolean wrapperFound = false;
if (wrapperMap == null) {
// process the wrapper settings as we have not done it before.
wrapperMap = WrapperUtils.mergeWrapperMap(client);
}
for (Iterator it = wrapperMap.keySet().iterator(); it.hasNext();) {
SimpleStringPattern pattern = (SimpleStringPattern)it.next();
if (pattern.doesMatch(filename)) {
keywordSubstitutionOptions = (KeywordSubstitutionOptions)wrapperMap.get(pattern);
wrapperFound = true;
break;
}
}
// if no wrappers are found to match the server and local settings, try
// the wrappers for this local directory
if (!wrapperFound && (directoryLevelWrappers != null) && (directoryLevelWrappers!=EMPTYWRAPPER)) {
for (Iterator it = directoryLevelWrappers.keySet().iterator(); it.hasNext();) {
SimpleStringPattern pattern = (SimpleStringPattern)it.next();
if (pattern.doesMatch(filename)) {
keywordSubstitutionOptions = (KeywordSubstitutionOptions)directoryLevelWrappers.get(pattern);
wrapperFound = true;
break;
}
}
}
return keywordSubstitutionOptions == KeywordSubstitutionOptions.BINARY;
}
/**
* Execute a command.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
if (files == null || files.length == 0) {
throw new CommandException("No files have been specified for " + //NOI18N
"adding.", CommandException.getLocalMessage("AddCommand.noFilesSpecified", null)); //NOI18N
}
client.ensureConnection();
clientServices = client;
setLocalDirectory(client.getLocalPath());
String directory = client.getLocalPath();
File cvsfolder = new File(directory, "CVS");
if (!cvsfolder.isDirectory()) {
//setFailed();
MessageEvent event = new MessageEvent(this, "cvs [add aborted]: there is no version here; do 'cvs checkout' first", true);
messageSent(event);
em.fireCVSEvent(event);
return ;
}
/*
newDirList = new HashMap();
*/
newDirList.clear();
super.execute(client, em);
requests = new LinkedList();
if (client.isFirstCommand()) {
requests.add(new RootRequest(client.getRepository()));
}
// sets the message argument -m .. one for all files being sent..
String message = getMessage();
if (message != null) {
message = message.trim();
}
if (message != null
&& message.length() > 0) {
addMessageRequest(message);
}
if (getKeywordSubst() != null && !getKeywordSubst().equals("")) { //NOI18N
requests.add(new ArgumentRequest("-k" + getKeywordSubst())); //NOI18N
}
try {
// current dir sent to server BEFORE and AFTER - kinda hack??
for (int i = 0; i < files.length; i++) {
addRequests(files[i]);
}
// now add the request that indicates the working directory for the
// command
requests.add(new DirectoryRequest(".", //NOI18N
client.getRepositoryForDirectory(getLocalDirectory())));
requests.addAll(argumentRequests);
argumentRequests.clear(); // MK sanity check.
requests.add(CommandRequest.ADD);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
private void addMessageRequest(String message) {
requests.add(new ArgumentRequest("-m")); //NOI18N
StringTokenizer token = new StringTokenizer(message, "\n", false); //NOI18N
boolean first = true;
while (token.hasMoreTokens()) {
if (first) {
requests.add(new ArgumentRequest(token.nextToken()));
first = false;
}
else {
requests.add(new ArgumentxRequest(token.nextToken()));
}
}
}
/**
* This method returns how the command would look like when typed on the
* command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("add "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* Method that is called while the command is being executed.
* Descendants can override this method to return a Builder instance
* that will parse the server's output and create data structures.
*/
public Builder createBuilder(EventManager eventManager) {
return new AddBuilder(eventManager, this);
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'm') {
setMessage(optArg);
}
else if (opt == 'k') {
KeywordSubstitutionOptions keywordSubst =
KeywordSubstitutionOptions.findKeywordSubstOption(optArg);
setKeywordSubst(keywordSubst);
}
else {
return false;
}
return true;
}
/**
* Returns a string indicating the available options.
*/
public String getOptString() {
return "m:k:"; //NOI18N
}
/**
* Listens for output of the command.
* If new directory is added, executes the createCvsFiles() method.
*/
public void messageSent(MessageEvent e) {
String str = e.getMessage();
if (str.endsWith(DIR_ADDED)) {
str = str.substring(DIRECTORY.length(), str.indexOf(DIR_ADDED)).trim();
createCvsFiles(str);
}
super.messageSent(e);
}
/**
* For new directory that was added to the repository, creates the admin
* files in CVS subdir.
*/
private void createCvsFiles(String newDirInRepository) {
String repository = newDirInRepository;
String dirName = repository;
if (dirName.lastIndexOf('/') >= 0) {
dirName = dirName.substring(dirName.lastIndexOf('/') + 1,
dirName.length());
}
if (newDirList.size() == 0) {
System.err.println("JavaCVS: Bug in AddCommand|createCvsFiles"); // NOI18N
System.err.println(" newDirInRepository = " + newDirInRepository); // NOI18N
return;
}
Paths paths = null;
for (Iterator i = newDirList.iterator(); i.hasNext();) {
paths = (Paths) i.next();
if (paths.getRepositoryPath().equals(newDirInRepository)) {
i.remove();
break;
}
}
String local = paths.getPartPath();
String part = paths.getRepositoryPath();
repository = paths.getRepositoryPath();
String tempDirName = part;
if (part.lastIndexOf('/') >= 0) {
tempDirName = part.substring(part.lastIndexOf('/') + 1,
part.length());
}
if (!tempDirName.equalsIgnoreCase(dirName)) {
System.err.println("JavaCVS: Bug in AddCommand|createCvsFiles"); // NOI18N
System.err.println(" newDirInRepository = " + newDirInRepository); // NOI18N
System.err.println(" tempDirName = " + tempDirName); // NOI18N
System.err.println(" dirName = " + dirName); // NOI18N
return;
}
try {
if (repository.startsWith(".")) { //NOI18N
repository = repository.substring(1);
}
clientServices.updateAdminData(local, repository, null);
createCvsTagFile(local, repository);
}
catch (IOException ex) {
System.err.println("TODO: couldn't create/update Cvs admin files"); // NOI18N
}
/*
Iterator it = newDirList.keySet().iterator();
while (it.hasNext())
{
String local = (String)it.next();
String part = (String)newDirList.get(local);
String tempDirName = part;
if (part.lastIndexOf('/') >= 0)
{
tempDirName = part.substring(part.lastIndexOf('/') + 1,
part.length());
}
if (tempDirName.equalsIgnoreCase(dirName))
{
try
{
clientServices.updateAdminData(local, repository, null);
createCvsTagFile(local, repository);
it.remove(); // hack.. in case 2 dirs being added have the same name??
break;
}
catch (IOException exc)
{
System.out.println("TODO: couldn't create/update Cvs admin files");
}
}
}
*/
}
private void createCvsTagFile(String local, String repository) throws IOException {
File current = new File(getLocalDirectory(), local);
File parent = current.getParentFile();
String tag = clientServices.getStickyTagForDirectory(parent);
if (tag != null) {
File tagFile = new File(current, "CVS/Tag"); // NOI18N
tagFile.createNewFile();
PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter(tagFile)));
w.println(tag);
w.close();
}
}
/**
* resets all switches in the command. After calling this method,
* the command should have no switches defined and should behave defaultly.
*/
public void resetCVSCommand() {
setMessage(null);
setKeywordSubst(null);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer();
if (getMessage() != null) {
toReturn.append("-m \""); //NOI18N
toReturn.append(getMessage());
toReturn.append("\" "); //NOI18N
}
if (getKeywordSubst() != null) {
toReturn.append("-k"); //NOI18N
toReturn.append(getKeywordSubst().toString());
toReturn.append(" "); //NOI18N
}
return toReturn.toString();
}
private static class Paths {
private final String partPath;
private final String repositoryPath;
public Paths(String partPath, String repositoryPath) {
this.partPath = partPath;
this.repositoryPath = repositoryPath;
}
public String getPartPath() {
return partPath;
}
public String getRepositoryPath() {
return repositoryPath;
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/add/AddInformation.java 0000644 0001753 0000144 00000005102 11175406776 027762 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.add;
import org.netbeans.lib.cvsclient.command.*;
/**
* Describes add information for a file. This is the result of doing a
* cvs add command. The fields in instances of this object are populated
* by response handlers.
* @author Thomas Singer
*/
public class AddInformation extends DefaultFileInfoContainer {
public static final String FILE_ADDED = "A"; //NOI18N
public static final String FILE_RESURRECTED = "U"; //NOI18N
public AddInformation() {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/annotate/ 0000755 0001753 0000144 00000000000 11175434236 025274 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/annotate/AnnotateBuilder.java 0000644 0001753 0000144 00000013704 11175406776 031234 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.annotate;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of a annotate information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
*/
public class AnnotateBuilder implements Builder {
private static final String UNKNOWN = ": nothing known about"; //NOI18N
private static final String ANNOTATING = "Annotations for "; //NOI18N
private static final String STARS = "***************"; //NOI18N
/**
* The Annotate object that is currently being built.
*/
private AnnotateInformation annotateInformation;
/**
* The event manager to use.
*/
private final EventManager eventManager;
private final String localPath;
private String relativeDirectory;
private int lineNum;
private File tempDir;
public AnnotateBuilder(EventManager eventManager, BasicCommand annotateCommand) {
this.eventManager = eventManager;
this.localPath = annotateCommand.getLocalDirectory();
tempDir = annotateCommand.getGlobalOptions().getTempDir();
}
public void outputDone() {
if (annotateInformation == null) {
return;
}
try {
annotateInformation.closeTempFile();
}
catch (IOException exc) {
// ignore
}
eventManager.fireCVSEvent(new FileInfoEvent(this, annotateInformation));
annotateInformation = null;
}
public void parseLine(String line, boolean isErrorMessage) {
if (isErrorMessage && line.startsWith(ANNOTATING)) {
outputDone();
annotateInformation = new AnnotateInformation(tempDir);
annotateInformation.setFile(createFile(line.substring(ANNOTATING.length())));
lineNum = 0;
return;
}
if (isErrorMessage && line.startsWith(STARS)) {
// skip
return;
}
if (!isErrorMessage) {
processLines(line);
}
}
private File createFile(String fileName) {
return new File(localPath, fileName);
}
public void parseEnhancedMessage(String key, Object value) {
}
private void processLines(String line) {
if (annotateInformation != null) {
try {
annotateInformation.addToTempFile(line);
}
catch (IOException exc) {
// just ignore, should not happen.. if it does the worst thing that happens is a annotate info without data..
}
}
/*
AnnotateLine annLine = processLine(line);
if (annotateInformation != null && annLine != null) {
annLine.setLineNum(lineNum);
annotateInformation.addLine(annLine);
lineNum++;
}
*/
}
public static AnnotateLine processLine(String line) {
int indexOpeningBracket = line.indexOf('(');
int indexClosingBracket = line.indexOf(')');
AnnotateLine annLine = null;
if (indexOpeningBracket > 0 && indexClosingBracket > indexOpeningBracket) {
String revision = line.substring(0, indexOpeningBracket).trim();
String userDate = line.substring(indexOpeningBracket + 1, indexClosingBracket);
String contents = line.substring(indexClosingBracket + 3);
int lastSpace = userDate.lastIndexOf(' ');
String user = userDate;
String date = userDate;
if (lastSpace > 0) {
user = userDate.substring(0, lastSpace).trim();
date = userDate.substring(lastSpace).trim();
}
annLine = new AnnotateLine();
annLine.setContent(contents);
annLine.setAuthor(user);
annLine.setDateString(date);
annLine.setRevision(revision);
}
return annLine;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/annotate/AnnotateCommand.java 0000644 0001753 0000144 00000023354 11175406776 031226 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.annotate;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The annotate command shows all lines of the file and annotates each line with cvs-related info.
* @author Milos Kleint
*/
public class AnnotateCommand extends BasicCommand {
/**
* The event manager to use
*/
protected EventManager eventManager;
/**
* Use head revision if a revision meeting criteria set by switches -r/-D
* (tag/date) is not found.
*/
private boolean useHeadIfNotFound;
/**
* equals the -D switch of command line cvs.
*/
private String annotateByDate;
/**
* Equals the -r switch of command-line cvs.
*/
private String annotateByRevision;
/**
* Construct a new diff command
*/
public AnnotateCommand() {
}
/**
* Create a builder for this command.
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventMan) {
return new AnnotateBuilder(eventMan, this);
}
/**
* Execute a command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests.
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
eventManager = em;
client.ensureConnection();
super.execute(client, em);
excludeBinaryFiles(requests);
try {
if (useHeadIfNotFound) {
requests.add(1, new ArgumentRequest("-f")); //NOI18N
}
if (annotateByDate != null && annotateByDate.length() > 0) {
requests.add(1, new ArgumentRequest("-D")); //NOI18N
requests.add(2, new ArgumentRequest(getAnnotateByDate()));
}
if (annotateByRevision != null && annotateByRevision.length() > 0) {
requests.add(1, new ArgumentRequest("-r")); //NOI18N
requests.add(2, new ArgumentRequest(getAnnotateByRevision()));
}
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.ANNOTATE);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
private void excludeBinaryFiles(java.util.List requests) {
Iterator it = requests.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof EntryRequest) {
EntryRequest req = (EntryRequest)obj;
if (req.getEntry().isBinary()) {
it.remove();
if (it.hasNext()) {
// removes also the follwoing modified/unchanged request
it.next();
it.remove();
}
}
}
}
}
/** called when server responses with "ok" or "error", (when the command finishes)
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* Getter for property useHeadIfNotFound.
* @return Value of property useHeadIfNotFound.
*/
public boolean isUseHeadIfNotFound() {
return useHeadIfNotFound;
}
/**
* Setter for property useHeadIfNotFound.
* @param useHeadIfNotFound New value of property useHeadIfNotFound.
*/
public void setUseHeadIfNotFound(boolean useHeadIfNotFound) {
this.useHeadIfNotFound = useHeadIfNotFound;
}
/**
* Getter for property annotateByDate.
* @return Value of property annotateByDate.
*/
public String getAnnotateByDate() {
return annotateByDate;
}
/**
* Setter for property annotateByDate.
* @param annotateByDate New value of property annotateByDate.
*/
public void setAnnotateByDate(String annotateByDate) {
this.annotateByDate = annotateByDate;
}
/**
* Getter for property annotateByRevision.
* @return Value of property annotateByRevision.
*/
public String getAnnotateByRevision() {
return annotateByRevision;
}
/**
* Setter for property annotateByRevision.
* @param annotateByRevision New value of property annotateByRevision.
*/
public void setAnnotateByRevision(String annotateByRevision) {
this.annotateByRevision = annotateByRevision;
}
/**
* This method returns how the command would looklike when typed on the command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("annotate "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName() + " "); //NOI18N
}
}
return toReturn.toString();
}
/** takes the arguments and sets the command. To be mainly
* used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'r') {
setAnnotateByRevision(optArg);
}
else if (opt == 'D') {
setAnnotateByDate(optArg);
}
else if (opt == 'f') {
setUseHeadIfNotFound(true);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "Rlr:D:f"; //NOI18N
}
/**
* resets all switches in the command. After calling this method,
* the command should have no switches defined and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setAnnotateByDate(null);
setAnnotateByRevision(null);
setUseHeadIfNotFound(false);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (getAnnotateByRevision() != null) {
toReturn.append("-r "); //NOI18N
toReturn.append(getAnnotateByRevision());
toReturn.append(" "); //NOI18N
}
if (getAnnotateByDate() != null) {
toReturn.append("-D "); //NOI18N
toReturn.append(getAnnotateByDate());
toReturn.append(" "); //NOI18N
}
if (isUseHeadIfNotFound()) {
toReturn.append("-f "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/annotate/AnnotateInformation.java 0000644 0001753 0000144 00000013714 11175406776 032134 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.annotate;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
/**
* Describes annotate information for a file. This is the result of doing a
* cvs annotate command. The fields in instances of this object are populated
* by response handlers.
* @author Milos Kleint
*/
public class AnnotateInformation extends FileInfoContainer {
/**
* The file, associated with thiz.
*/
private File file;
/**
* List of lines stored here.
*/
private List linesList;
private Iterator iterator;
private File tempFile;
private File tempDir;
private BufferedOutputStream tempOutStream;
public AnnotateInformation() {
this.tempDir = null;
}
public AnnotateInformation(File tempDir) {
this.tempDir = tempDir;
}
/**
* Getter for property file.
* @return Value of property file.
*/
public File getFile() {
return file;
}
/**
* Setter for property file.
* @param file New value of property file.
*/
public void setFile(File file) {
this.file = file;
}
/**
* Return a string representation of this object. Useful for debugging.
*/
public String toString() {
StringBuffer buf = new StringBuffer(30);
buf.append("\nFile: " + ((file != null)?file.getAbsolutePath():"null")); //NOI18N
return buf.toString();
}
public AnnotateLine createAnnotateLine() {
return new AnnotateLine();
}
public void addLine(AnnotateLine line) {
linesList.add(line);
}
public AnnotateLine getFirstLine() {
if (linesList == null) {
linesList = createLinesList();
}
iterator = linesList.iterator();
return getNextLine();
}
public AnnotateLine getNextLine() {
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return null;
}
return (AnnotateLine)iterator.next();
}
/**
* Adds the specified line to the temporary file.
*/
protected void addToTempFile(String line) throws IOException {
if (tempOutStream == null) {
try {
tempFile = File.createTempFile("ann", ".cvs", tempDir); //NOI18N
tempFile.deleteOnExit();
tempOutStream = new BufferedOutputStream(
new FileOutputStream(tempFile));
}
catch (IOException ex) {
// TODO
}
}
tempOutStream.write(line.getBytes());
tempOutStream.write('\n');
}
protected void closeTempFile() throws IOException {
if (tempOutStream == null) {
return;
}
try {
tempOutStream.flush();
} finally {
tempOutStream.close();
}
}
public File getTempFile() {
return tempFile;
}
private List createLinesList() {
List toReturn = new LinkedList();
BufferedReader reader = null;
if (tempFile == null) {
return toReturn;
}
try {
reader = new BufferedReader(new FileReader(tempFile));
String line = reader.readLine();
int lineNum = 1;
while (line != null) {
AnnotateLine annLine = AnnotateBuilder.processLine(line);
if (annLine != null) {
annLine.setLineNum(lineNum);
toReturn.add(annLine);
lineNum++;
}
line = reader.readLine();
}
}
catch (IOException exc) {
}
finally {
try {
if (reader != null) {
reader.close();
}
}
catch (IOException ex2) {
}
}
return toReturn;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/annotate/AnnotateLine.java 0000644 0001753 0000144 00000010500 11175406776 030524 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.annotate;
import java.text.*;
import java.util.*;
/**
* @author Thomas Singer
*/
public class AnnotateLine {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd-MMM-yy", //NOI18N
Locale.US);
private String author;
private String revision;
private Date date;
private String dateString;
private String content;
private int lineNum;
public AnnotateLine() {
}
/**
* Returns the author of this line.
*/
public String getAuthor() {
return author;
}
/**
* Sets the author of this line.
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* Returns the revision of this line.
*/
public String getRevision() {
return revision;
}
/**
* Sets the revision of this line.
*/
public void setRevision(String revision) {
this.revision = revision;
}
/**
* Returns the date of this line.
*/
public Date getDate() {
return date;
}
/**
* Returns the date in original String-representation of this line.
*/
public String getDateString() {
return dateString;
}
/**
* Sets the date of this line.
*/
public void setDateString(String dateString) {
this.dateString = dateString;
try {
this.date = DATE_FORMAT.parse(dateString);
}
catch (ParseException ex) {
// print stacktrace, because it's a bug
ex.printStackTrace();
}
}
/**
* Return the line's content.
*/
public String getContent() {
return content;
}
/**
* Sets the line's content.
*/
public void setContent(String content) {
this.content = content;
}
/**
* Returns the line's number. It's 1 based.
*/
public int getLineNum() {
return lineNum;
}
/**
* Returns the line's number.
*/
public Integer getLineNumInteger() {
return new Integer(lineNum);
}
/**
* Sets the line's number.
*/
public void setLineNum(int lineNum) {
this.lineNum = lineNum;
}
} netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/annotate/RannotateCommand.java 0000644 0001753 0000144 00000027343 11175406776 031412 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.annotate;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The rannotate command is similar to anootate, but doens't operate on currently checked
* out sources.
*
* @author MIlos Kleint
*/
public class RannotateCommand extends BasicCommand {
/**
* The modules to checkout. These names are unexpanded and will be passed
* to a module-expansion request.
*/
private final List modules = new LinkedList();
/**
* The expanded modules.
*/
private final List expandedModules = new LinkedList();
/**
* Use head revision if a revision meeting criteria set by switches -r/-D
* (tag/date) is not found.
*/
private boolean useHeadIfNotFound;
/**
* equals the -D switch of command line cvs.
*/
private String annotateByDate;
/**
* Equals the -r switch of command-line cvs.
*/
private String annotateByRevision;
/**
* Holds value of property headerAndDescOnly.
*/
private boolean headerAndDescOnly;
public RannotateCommand() {
resetCVSCommand();
}
/**
* Set the modules to export.
* @param theModules the names of the modules to export
*/
public void setModule(String module) {
modules.add(module);
}
/**
* clears the list of modules for export.
*/
public void clearModules() {
this.modules.clear();
}
/**
* Set the modules to export.
* @param theModules the names of the modules to export
*/
public void setModules(String[] modules) {
clearModules();
if (modules == null) {
return;
}
for (int i = 0; i < modules.length; i++) {
String module = modules[i];
this.modules.add(module);
}
}
public String[] getModules() {
String[] mods = new String[modules.size()];
mods = (String[])modules.toArray(mods);
return mods;
}
private void processExistingModules(String localPath) {
if (expandedModules.size() == 0) {
return;
}
String[] directories = new String[expandedModules.size()];
directories = (String[])expandedModules.toArray(directories);
setModules(directories);
}
/**
* Execute this command.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
requests = new LinkedList();
if (client.isFirstCommand()) {
requests.add(new RootRequest(client.getRepository()));
}
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
requests.add(new ArgumentRequest(module));
}
expandedModules.clear();
requests.add(new DirectoryRequest(".", client.getRepository())); //NOI18N
requests.add(new ExpandModulesRequest());
try {
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
requests.clear();
postExpansionExecute(client, em);
}
/**
* This is called when the server has responded to an expand-modules
* request.
*/
public void moduleExpanded(ModuleExpansionEvent e) {
expandedModules.add(e.getModule());
}
/**
* Execute this command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
private void postExpansionExecute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
// processExistingModules(client.getLocalPath());
super.execute(client, em);
//
// moved modules code to the end of the other arguments --GAR
//
if (!isRecursive())
{
requests.add(1, new ArgumentRequest("-l")); //NOI18N
}
if (useHeadIfNotFound) {
requests.add(1, new ArgumentRequest("-f")); //NOI18N
}
if (annotateByDate != null && annotateByDate.length() > 0) {
requests.add(1, new ArgumentRequest("-D")); //NOI18N
requests.add(2, new ArgumentRequest(getAnnotateByDate()));
}
if (annotateByRevision != null && annotateByRevision.length() > 0) {
requests.add(1, new ArgumentRequest("-r")); //NOI18N
requests.add(2, new ArgumentRequest(getAnnotateByRevision()));
}
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
requests.add(new ArgumentRequest(module));
}
requests.add(new DirectoryRequest(".", client.getRepository())); //NOI18N
requests.add(CommandRequest.RANNOTATE);
try {
client.processRequests(requests);
requests.clear();
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
}
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("rannotate "); //NOI18N
toReturn.append(getCVSArguments());
if (modules != null && modules.size() > 0) {
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
toReturn.append(module);
toReturn.append(' ');
}
}
else {
String localizedMsg = CommandException.getLocalMessage("ExportCommand.moduleEmpty.text"); //NOI18N
toReturn.append(" "); //NOI18N
toReturn.append(localizedMsg);
}
return toReturn.toString();
}
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (getAnnotateByRevision() != null) {
toReturn.append("-r "); //NOI18N
toReturn.append(getAnnotateByRevision());
toReturn.append(" "); //NOI18N
}
if (getAnnotateByDate() != null) {
toReturn.append("-D "); //NOI18N
toReturn.append(getAnnotateByDate());
toReturn.append(" "); //NOI18N
}
if (isUseHeadIfNotFound()) {
toReturn.append("-f "); //NOI18N
}
return toReturn.toString();
}
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'r') {
setAnnotateByRevision(optArg);
}
else if (opt == 'D') {
setAnnotateByDate(optArg);
}
else if (opt == 'f') {
setUseHeadIfNotFound(true);
}
else {
return false;
}
return true;
}
public void resetCVSCommand() {
setRecursive(true);
setAnnotateByDate(null);
setAnnotateByRevision(null);
setUseHeadIfNotFound(false);
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "Rlr:D:f"; //NOI18N
}
/**
* Create a builder for this command.
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventMan) {
return new AnnotateBuilder(eventMan, this);
}
/** called when server responses with "ok" or "error", (when the command finishes)
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* Getter for property useHeadIfNotFound.
* @return Value of property useHeadIfNotFound.
*/
public boolean isUseHeadIfNotFound() {
return useHeadIfNotFound;
}
/**
* Setter for property useHeadIfNotFound.
* @param useHeadIfNotFound New value of property useHeadIfNotFound.
*/
public void setUseHeadIfNotFound(boolean useHeadIfNotFound) {
this.useHeadIfNotFound = useHeadIfNotFound;
}
/**
* Getter for property annotateByDate.
* @return Value of property annotateByDate.
*/
public String getAnnotateByDate() {
return annotateByDate;
}
/**
* Setter for property annotateByDate.
* @param annotateByDate New value of property annotateByDate.
*/
public void setAnnotateByDate(String annotateByDate) {
this.annotateByDate = annotateByDate;
}
/**
* Getter for property annotateByRevision.
* @return Value of property annotateByRevision.
*/
public String getAnnotateByRevision() {
return annotateByRevision;
}
/**
* Setter for property annotateByRevision.
* @param annotateByRevision New value of property annotateByRevision.
*/
public void setAnnotateByRevision(String annotateByRevision) {
this.annotateByRevision = annotateByRevision;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/checkout/ 0000755 0001753 0000144 00000000000 11175434236 025270 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/checkout/CheckoutCommand.java 0000644 0001753 0000144 00000073151 11175406776 031216 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.checkout;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.command.update.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The checkout command.
* This handles the sending of the requests and the processing of the responses
* from the server.
*
* @author Robert Greig
*/
public class CheckoutCommand extends BasicCommand
implements TemporaryFileCreator {
private static final String UPDATING = ": Updating "; // NOI18N
/**
* A store of potentially empty directories. When a directory has a file
* in it, it is removed from this set. This set allows the prune option
* to be implemented.
*/
private final Set emptyDirectories = new HashSet();
/**
* The modules to checkout. These names are unexpanded and will be passed
* to a module-expansion request.
*/
private final List modules = new LinkedList();
/**
* The expanded modules.
*/
private final List expandedModules = new LinkedList();
/**
* Will force the checkout command to display only a list of modules.
*/
private boolean showModules;
/**
* if set, will display just a list of modules with statuses.
*/
private boolean showModulesWithStatus;
/**
* if set, will redirect the output of the command to standard output.
*/
private boolean pipeToOutput;
/**
* Whether to prune directories, i.e. remove any directories that do not
* contain any files. This is the -P option in command-line CVS.
*/
private boolean pruneDirectories;
/**
* Resets any sticky tags/dates/options imposed on the updated file(s).
*/
private boolean resetStickyOnes;
/**
* Use head revision if a revision meeting criteria set by switches -r/-D
* (tag/date) is not found.
*/
private boolean useHeadIfNotFound;
/**
* Don't shorten module paths if -d specified.
*/
private boolean notShortenPaths;
/**
* Whether notShortenPaths
was explicitly set.
*/
private boolean isNotShortenSet;
/**
* Forces a checkout of a revision that was current at specified date.
*/
private String checkoutByDate;
/**
* Forces a checkout of specified revision. Can be a number/tag/branch
*/
private String checkoutByRevision;
/**
* performs checkout to specified directory other then the module.
*/
private String checkoutDirectory;
/**
* Use this keyword substitution for the command.
* does not include the -k switch part.
*/
private KeywordSubstitutionOptions keywordSubst;
/**
* Do not run module program (if any).
*/
private boolean notRunModuleProgram;
/** Active during execute. */
private ClientServices client;
/**
* Construct a new checkout command.
* @param recursive whether to do a recursive checkout
* @param modules an array of modules names to checkout
*/
public CheckoutCommand(boolean recursive, String[] modules) {
resetCVSCommand();
setRecursive(recursive);
setModules(modules);
}
/**
* Construct a new checkout command.
* @param recursive whether to do a recursive checkout
* @param module the module to checkout
*/
public CheckoutCommand(boolean recursive, String module) {
resetCVSCommand();
setRecursive(recursive);
setModule(module);
}
/**
* Construct a checkout command, with default values for options.
*/
public CheckoutCommand() {
resetCVSCommand();
setRecursive(true);
}
/**
* Set the modules to checkout.
* @param theModules the names (it's like relative path) of the modules to checkout
*/
public void setModule(String module) {
modules.add(module);
}
/**
* clears the list of modules for checkout.
*/
public void clearModules() {
this.modules.clear();
}
/**
* Set the modules to checkout.
* @param theModules the names of the modules to checkout
*/
public void setModules(String[] modules) {
clearModules();
for (int i = 0; i < modules.length; i++) {
String module = modules[i];
this.modules.add(module);
}
}
public String[] getModules() {
String[] mods = new String[modules.size()];
mods = (String[])modules.toArray(mods);
return mods;
}
/**
* Handle modules that are already checked out. We check whether a
* module has been checked out and if so we add it to the list of
* directories that the superclass must send Modified requests for etc.
*/
private void processExistingModules(String localPath) {
if (expandedModules.size() == 0) {
return;
}
List list = new ArrayList(expandedModules.size());
for (Iterator it = expandedModules.iterator(); it.hasNext();) {
String moduleName = (String)it.next();
if (moduleName.equals(".")) { //NOI18N
list.add(new File(localPath));
break;
}
File moduleDir = null;
final File moduleFile = new File(localPath, moduleName);
if (moduleFile.isFile()) {
moduleDir = moduleFile.getParentFile();
}
else {
moduleDir = moduleFile;
}
final File moduleCVSDir = new File(moduleDir, "CVS/Repository"); //NOI18N
if (moduleCVSDir.exists()) {
list.add(moduleFile);
}
}
File[] directories = new File[list.size()];
directories = (File[])list.toArray(directories);
setFiles(directories);
}
/**
* Execute this command.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
this.client = client;
try {
requests = new LinkedList();
if (client.isFirstCommand()) {
requests.add(new RootRequest(client.getRepository()));
}
if (showModules || showModulesWithStatus) {
// we need to initialize the builder first (is done in BuildableCommand.execute()
// but we can't run it because of teh BasicCommand's execute and
// it's feature that adds the files request to the request list.
if (builder == null && !isBuilderSet()) {
builder = createBuilder(em);
}
// special handling for -c -s switches.
if (showModules) {
requests.add(new ArgumentRequest("-c")); //NOI18N
}
if (showModulesWithStatus) {
requests.add(new ArgumentRequest("-s")); //NOI18N
}
requests.add(CommandRequest.CHECKOUT);
try {
client.processRequests(requests);
requests.clear();
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
throw new CommandException(ex, CommandException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
return;
}
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
requests.add(new ArgumentRequest(module));
}
expandedModules.clear();
requests.add(new DirectoryRequest(".", client.getRepository())); //NOI18N
requests.add(new RootRequest(client.getRepository()));
requests.add(new ExpandModulesRequest());
try {
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
requests.clear();
postExpansionExecute(client, em);
} finally {
this.client = null;
}
}
/**
* The result from this command is used only when the getFiles() returns null or empty array.
* in such a case and when this method returns true, it is assumed the localpath should be taken
* as the 'default' file for the building of requests.
* in checkout we operate with modules rather then files. This produces problems in the following situation.
* If you have something already checked out and want to checkout another module that is not checked out yet,
* then there's nothing to be translated from modules to files. and in such a case the localpathis assumed,
* which includes non-relevant already checked out directories..
*/
protected boolean assumeLocalPathWhenUnspecified() {
return false;
}
/**
* This is called when the server has responded to an expand-modules
* request.
*/
public void moduleExpanded(ModuleExpansionEvent e) {
expandedModules.add(e.getModule());
}
/**
* Execute this command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
private void postExpansionExecute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
// we first test whether the modules specified actually exist
// checked out already. If so, we must work something like an update
// command and send modified files to the server.
processExistingModules(client.getLocalPath());
// the sending of the Modified requests and so on is handled in the
// superclass.
super.execute(client, em);
//
// moved modules code to the end of the other arguments --GAR
//
int index = requests.size();
final int FIRST_INDEX = 0;
final int SECOND_INDEX = 1;
if (!isRecursive()) {
requests.add(FIRST_INDEX, new ArgumentRequest("-l")); //NOI18N
}
if (pipeToOutput) {
requests.add(FIRST_INDEX, new ArgumentRequest("-p")); //NOI18N
}
if (resetStickyOnes) {
requests.add(FIRST_INDEX, new ArgumentRequest("-A")); //NOI18N
}
if (useHeadIfNotFound) {
requests.add(FIRST_INDEX, new ArgumentRequest("-f")); //NOI18N
}
if (isNotShortenPaths()) {
requests.add(FIRST_INDEX, new ArgumentRequest("-N")); //NOI18N
}
if (notRunModuleProgram) {
requests.add(FIRST_INDEX, new ArgumentRequest("-n")); //NOI18N
}
if (checkoutByDate != null && checkoutByDate.length() > 0) {
requests.add(FIRST_INDEX, new ArgumentRequest("-D")); //NOI18N
requests.add(SECOND_INDEX, new ArgumentRequest(getCheckoutByDate()));
}
if (checkoutByRevision != null && checkoutByRevision.length() > 0) {
requests.add(FIRST_INDEX, new ArgumentRequest("-r")); //NOI18N
requests.add(SECOND_INDEX, new ArgumentRequest(getCheckoutByRevision()));
}
if (checkoutDirectory != null && (!checkoutDirectory.equals(""))) {
requests.add(FIRST_INDEX, new ArgumentRequest("-d")); //NOI18N
requests.add(SECOND_INDEX, new ArgumentRequest(getCheckoutDirectory()));
}
if (getKeywordSubst() != null) {
requests.add(FIRST_INDEX, new ArgumentRequest("-k" + getKeywordSubst())); //NOI18N
}
index = requests.size() - index; // The end of our arguments
// Add a -- before the first file name just in case it looks like an option.
requests.add(index++, new ArgumentRequest("--")); // NOI18N
// Note that modules might be null and still be valid because
// for -c, -s switches no module has to be selected
// You might also think that we should pass in expandedModules here
// but according to the spec that would be wrong because of the -d
// flag.
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
requests.add(index++, new ArgumentRequest(module));
}
requests.add(new DirectoryRequest(".", client.getRepository())); //NOI18N
requests.add(CommandRequest.CHECKOUT);
try {
client.processRequests(requests);
if (pruneDirectories) {
pruneEmptyDirectories();
}
requests.clear();
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
}
/**
* Getter for property showModules.
* @return Value of property showModules.
*/
public boolean isShowModules() {
return showModules;
}
/**
* Setter for property showModules.
* @param showModules New value of property showModules.
*/
public void setShowModules(boolean showModules) {
this.showModules = showModules;
}
/**
* Getter for property showModulesWithStatus.
* @return Value of property showModulesWithStatus.
*/
public boolean isShowModulesWithStatus() {
return showModulesWithStatus;
}
/**
* Setter for property showModulesWithStatus.
* @param showModulesWithStatus New value of property showModulesWithStatus.
*/
public void setShowModulesWithStatus(boolean showModulesWithStatus) {
this.showModulesWithStatus = showModulesWithStatus;
}
/**
* Set whether to prune directories.
* This is the -P option in the command-line CVS.
*/
public void setPruneDirectories(boolean pruneDirectories) {
this.pruneDirectories = pruneDirectories;
}
/**
* Get whether to prune directories.
* @return true if directories should be removed if they contain no files,
* false otherwise.
*/
public boolean getPruneDirectories() {
return pruneDirectories;
}
/**
* Getter for property pipeToOutput.
* @return Value of property pipeToOutput.
*/
public boolean isPipeToOutput() {
return pipeToOutput;
}
/**
* Setter for property pipeToOutput.
* @param pipeToOutput New value of property pipeToOutput.
*/
public void setPipeToOutput(boolean pipeToOutput) {
this.pipeToOutput = pipeToOutput;
}
/**
* Getter for property resetStickyOnes.
* @return Value of property resetStickyOnes.
*/
public boolean isResetStickyOnes() {
return resetStickyOnes;
}
/**
* Setter for property resetStickyOnes.
* @param resetStickyOnes New value of property resetStickyOnes.
*/
public void setResetStickyOnes(boolean resetStickyOnes) {
this.resetStickyOnes = resetStickyOnes;
}
/**
* Getter for property useHeadIfNotFound.
* @return Value of property useHeadIfNotFound.
*/
public boolean isUseHeadIfNotFound() {
return useHeadIfNotFound;
}
/**
* Setter for property useHeadIfNotFound.
* @param useHeadIfNotFound New value of property useHeadIfNotFound.
*/
public void setUseHeadIfNotFound(boolean useHeadIfNotFound) {
this.useHeadIfNotFound = useHeadIfNotFound;
}
/**
* Getter for property notShortenPaths.
* @return Value of property notShortenPaths.
*/
public boolean isNotShortenPaths() {
// Use the same logic as cvs from cvshome.org.
return notShortenPaths || (!isNotShortenSet && checkoutDirectory == null);
}
/**
* Setter for property notShortenPaths.
* @param notShortenPaths New value of property notShortenPaths.
*/
public void setNotShortenPaths(boolean notShortenPaths) {
this.notShortenPaths = notShortenPaths;
isNotShortenSet = true;
}
/**
* Getter for property notRunModuleProgram.
* @return Value of property notRunModuleProgram.
*/
public boolean isNotRunModuleProgram() {
return notRunModuleProgram;
}
/**
* Setter for property notRunModuleProgram.
* @param notRunModuleProgram New value of property notRunModuleProgram.
*/
public void setNotRunModuleProgram(boolean notRunModuleProgram) {
this.notRunModuleProgram = notRunModuleProgram;
}
/**
* Getter for property checkoutByDate.
* @return Value of property checkoutByDate.
*/
public String getCheckoutByDate() {
return checkoutByDate;
}
/**
* Setter for property checkoutByDate.
* @param checkoutByDate New value of property checkoutByDate.
*/
public void setCheckoutByDate(String checkoutByDate) {
this.checkoutByDate = checkoutByDate;
}
/**
* Getter for property checkoutByRevision.
* @return Value of property checkoutByRevision.
*/
public String getCheckoutByRevision() {
return checkoutByRevision;
}
/**
* Setter for property checkoutByRevision.
* @param checkoutByRevision New value of property checkoutByRevision.
*/
public void setCheckoutByRevision(String checkoutByRevision) {
this.checkoutByRevision = checkoutByRevision;
}
/** Getter for property checkoutDirectory.
* @return Value of property checkoutDirectory.
*/
public String getCheckoutDirectory() {
return this.checkoutDirectory;
}
/** Setter for property checkoutDirectory.
* @param checkoutDirectory New value of property checkoutDirectory.
*/
public void setCheckoutDirectory(String checkoutDirectory) {
this.checkoutDirectory = checkoutDirectory;
}
/**
* Getter for property keywordSubst.
* @return Value of property keywordSubst.
*/
public KeywordSubstitutionOptions getKeywordSubst() {
return keywordSubst;
}
/**
* Setter for property keywordSubst.
* @param keywordSubst New value of property keywordSubst.
*/
public void setKeywordSubst(KeywordSubstitutionOptions keywordSubst) {
this.keywordSubst = keywordSubst;
}
public Builder createBuilder(EventManager eventMan) {
if (isShowModules() || isShowModulesWithStatus()) {
return new ModuleListBuilder(eventMan, this);
}
if (isPipeToOutput()) {
return new PipedFilesBuilder(eventMan, this, this);
}
return new UpdateBuilder(eventMan, getLocalDirectory());
}
public File createTempFile(String filename) throws IOException {
File temp = File.createTempFile("cvs", ".dff", getGlobalOptions().getTempDir()); //NOI18N
temp.deleteOnExit();
return temp;
}
/**
* This method returns how the command would looklike when typed on the command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("checkout "); //NOI18N
toReturn.append(getCVSArguments());
if (!isShowModules() && !isShowModulesWithStatus()) {
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
toReturn.append(module);
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file).
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'c') {
setShowModules(true);
}
else if (opt == 's') {
setShowModulesWithStatus(true);
}
else if (opt == 'p') {
setPipeToOutput(true);
}
else if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'A') {
setResetStickyOnes(true);
}
else if (opt == 'f') {
setUseHeadIfNotFound(true);
}
else if (opt == 'P') {
setPruneDirectories(true);
}
else if (opt == 'D') {
setCheckoutByDate(optArg.trim());
}
else if (opt == 'r') {
setCheckoutByRevision(optArg.trim());
}
else if (opt == 'd') {
setCheckoutDirectory(optArg);
}
else if (opt == 'N') {
setNotShortenPaths(true);
}
else if (opt == 'n') {
setNotRunModuleProgram(true);
}
else if (opt == 'k') {
KeywordSubstitutionOptions keywordSubst =
KeywordSubstitutionOptions.findKeywordSubstOption(optArg);
setKeywordSubst(keywordSubst);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "cnpslNPRAD:r:fk:d:"; //NOI18N
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setShowModules(false);
setShowModulesWithStatus(false);
setPipeToOutput(false);
setRecursive(true);
setResetStickyOnes(false);
setUseHeadIfNotFound(false);
setCheckoutByDate(null);
setCheckoutByRevision(null);
setKeywordSubst(null);
setPruneDirectories(false);
setNotShortenPaths(false);
isNotShortenSet = false;
setNotRunModuleProgram(false);
setCheckoutDirectory(null);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (isShowModules()) {
toReturn.append("-c "); //NOI18N
}
if (isShowModulesWithStatus()) {
toReturn.append("-s "); //NOI18N
}
if (isPipeToOutput()) {
toReturn.append("-p "); //NOI18N
}
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (isResetStickyOnes()) {
toReturn.append("-A "); //NOI18N
}
if (isUseHeadIfNotFound()) {
toReturn.append("-f "); //NOI18N
}
if (getPruneDirectories()) {
toReturn.append("-P "); //NOI18N
}
if (isNotShortenPaths()) {
toReturn.append("-N "); // NOI18N
}
if (isNotRunModuleProgram()) {
toReturn.append("-n "); // NOI18N
}
if (getKeywordSubst() != null) {
toReturn.append("-k"); //NOI18N
toReturn.append(getKeywordSubst());
toReturn.append(' ');
}
if (getCheckoutByRevision() != null && getCheckoutByRevision().length() > 0) {
toReturn.append("-r "); //NOI18N
toReturn.append(getCheckoutByRevision());
toReturn.append(' ');
}
if (getCheckoutByDate() != null && getCheckoutByDate().length() > 0) {
toReturn.append("-D "); //NOI18N
toReturn.append(getCheckoutByDate());
toReturn.append(' ');
}
if (getCheckoutDirectory() != null) {
toReturn.append("-d "); //NOI18N
toReturn.append(getCheckoutDirectory());
toReturn.append(" "); //NOI18N
}
return toReturn.toString();
}
/**
* Called when the server wants to send a message to be displayed to
* the user. The message is only for information purposes and clients
* can choose to ignore these messages if they wish.
* @param e the event
*/
public void messageSent(MessageEvent e) {
super.messageSent(e);
// we use this event to determine which directories need to be checked
// for updating
if (pruneDirectories &&
e.getMessage().indexOf(UPDATING) > 0) {
String relPath = e.getMessage().substring(e.getMessage().indexOf(UPDATING) + UPDATING.length());
File file = new File(getLocalDirectory(), relPath);
// do not consider the topmost directory for pruning
if (relPath.indexOf('/') != -1) {
emptyDirectories.add(file);
}
}
}
/**
* Prunes a directory, recursively pruning its subdirectories
* @param directory the directory to prune
*/
private boolean pruneEmptyDirectory(File directory) throws IOException {
boolean empty = true;
final File[] contents = directory.listFiles();
// should never be null, but just in case...
if (contents != null) {
for (int i = 0; i < contents.length; i++) {
if (contents[i].isFile()) {
empty = false;
}
else {
if (!contents[i].getName().equals("CVS")) { //NOI18N
empty = pruneEmptyDirectory(contents[i]);
}
}
if (!empty) {
break;
}
}
if (empty) {
// check this is a CVS directory and not some directory the user
// has stupidly called CVS...
final File entriesFile = new File(directory, "CVS/Entries"); //NOI18N
if (entriesFile.exists()) {
final File adminDir = new File(directory, "CVS"); //NOI18N
final File[] adminFiles = adminDir.listFiles();
for (int i = 0; i < adminFiles.length; i++) {
adminFiles[i].delete();
}
adminDir.delete();
directory.delete();
client.removeEntry(directory);
}
}
}
return empty;
}
/**
* Remove any directories that don't contain any files
*/
private void pruneEmptyDirectories() throws IOException {
final Iterator it = emptyDirectories.iterator();
while (it.hasNext()) {
final File dir = (File)it.next();
// we might have deleted it already (due to recursive delete)
// so we need to check existence
if (dir.exists()) {
pruneEmptyDirectory(dir);
}
}
emptyDirectories.clear();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/checkout/ModuleListBuilder.java 0000644 0001753 0000144 00000010303 11175406776 031530 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.checkout;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of module list information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
*/
public class ModuleListBuilder implements Builder {
/**
* The module object that is currently being built.
*/
private ModuleListInformation moduleInformation;
/**
* The event manager to use.
*/
private final EventManager eventManager;
private final CheckoutCommand checkoutCommand;
public ModuleListBuilder(EventManager eventMan, CheckoutCommand comm) {
eventManager = eventMan;
checkoutCommand = comm;
}
public void outputDone() {
if (moduleInformation != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, moduleInformation));
moduleInformation = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
line = line.replace('\t', ' ');
if (!line.startsWith(" ")) { //NOI18N
processModule(line, true);
}
else {
processModule(line, false);
}
}
protected void processModule(String line, boolean firstLine) {
StringTokenizer tok = new StringTokenizer(line, " ", false); //NOI18N
if (firstLine) {
outputDone();
moduleInformation = new ModuleListInformation();
String modName = tok.nextToken();
moduleInformation.setModuleName(modName);
if (checkoutCommand.isShowModulesWithStatus()) {
String stat = tok.nextToken();
moduleInformation.setModuleStatus(stat);
}
}
while (tok.hasMoreTokens()) {
String nextTok = tok.nextToken();
if (nextTok.startsWith("-")) { //NOI18N
moduleInformation.setType(nextTok);
continue;
}
moduleInformation.addPath(nextTok);
}
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/checkout/ModuleListInformation.java 0000644 0001753 0000144 00000006535 11175406776 032443 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.checkout;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
/**
* Object containing information about various modules defined in the repository.
* Is parsed from the output of cvs checkout -c and cvs checkout -s.
* @author Milos Kleint
*/
public class ModuleListInformation extends FileInfoContainer {
private String moduleName;
private String moduleStatus;
private final StringBuffer paths = new StringBuffer();
private String type;
public ModuleListInformation() {
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getModuleStatus() {
return moduleStatus;
}
public void setModuleStatus(String moduleStatus) {
this.moduleStatus = moduleStatus;
}
public String getPaths() {
return paths.toString();
}
public void addPath(String path) {
if (paths.length() > 0) {
paths.append(' ');
}
paths.append(path);
}
public File getFile() {
return null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/commit/ 0000755 0001753 0000144 00000000000 11175434236 024753 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/commit/CommitBuilder.java 0000644 0001753 0000144 00000025030 11175406777 030366 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.commit;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of update information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
*/
public class CommitBuilder
implements Builder {
/**
* Parsing constants.
*/
public static final String UNKNOWN = "commit: nothing known about `"; //NOI18N
public static final String EXAM_DIR = ": Examining"; //NOI18N
public static final String REMOVING = "Removing "; //NOI18N
public static final String NEW_REVISION = "new revision:"; //NOI18N
public static final String INITIAL_REVISION = "initial revision:"; //NOI18N
public static final String DELETED_REVISION = "delete"; //NOI18N
public static final String DONE = "done"; //NOI18N
public static final String RCS_FILE = "RCS file: "; //NOI18N
public static final String ADD = "commit: use `cvs add' to create an entry for "; //NOI18N
public static final String COMMITTED = " <-- "; // NOI18N
/**
* The status object that is currently being built.
*/
private CommitInformation commitInformation;
/**
* The directory in which the file being processed lives. This is
* absolute inside the local directory
*/
private File fileDirectory;
/**
* The event manager to use.
*/
private final EventManager eventManager;
private final String localPath;
private final String repositoryRoot;
private boolean isAdding;
public CommitBuilder(EventManager eventManager, String localPath, String repositoryRoot) {
this.eventManager = eventManager;
this.localPath = localPath;
this.repositoryRoot = repositoryRoot;
}
public void outputDone() {
if (commitInformation != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, commitInformation));
commitInformation = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
int c;
if (line.indexOf(UNKNOWN) >= 0) {
outputDone();
processUnknownFile(line.substring(line.indexOf(UNKNOWN) + UNKNOWN.length()).trim());
}
else if (line.indexOf(ADD) > 0) {
processToAddFile(line.substring(line.indexOf(ADD) + ADD.length()).trim());
}
else if ((c = line.indexOf(COMMITTED)) > 0) {
outputDone();
String fileName = line.substring(c + COMMITTED.length()).trim();
int nameIndex = fileName.lastIndexOf('/');
if (nameIndex != -1) { //#73181 happens with 1.12 servers: /usr/cvsrepo/Java112/nbproject/project.properties,v <-- nbproject/project.properties
fileName = fileName.substring(nameIndex+1);
}
File file;
if (fileDirectory == null) {
String reposPath = line.substring(0, c).trim();
if (reposPath.startsWith(repositoryRoot)) {
reposPath = reposPath.substring(repositoryRoot.length());
if (reposPath.startsWith("/")) reposPath = reposPath.substring(1);
}
c = reposPath.lastIndexOf('/');
if (c > 0) reposPath = reposPath.substring(0, c); // remove the file name
file = findFile(fileName, reposPath);
} else {
file = new File(fileDirectory, fileName);
}
processFile(file);
if (isAdding) {
commitInformation.setType(CommitInformation.ADDED);
isAdding = false;
}
else {
commitInformation.setType(CommitInformation.CHANGED);
}
}
else if (line.startsWith(REMOVING)) {
outputDone();
processFile(line.substring(REMOVING.length(), line.length() - 1));
// - 1 means to cut the ';' character
commitInformation.setType(CommitInformation.REMOVED);
}
else if (line.indexOf(EXAM_DIR) >= 0) {
fileDirectory = new File(localPath, line.substring(line.indexOf(EXAM_DIR) + EXAM_DIR.length()).trim());
}
else if (line.startsWith(RCS_FILE)) {
isAdding = true;
}
else if (line.startsWith(DONE)) {
outputDone();
}
else if (line.startsWith(INITIAL_REVISION)) {
processRevision(line.substring(INITIAL_REVISION.length()));
commitInformation.setType(CommitInformation.ADDED);
}
else if (line.startsWith(NEW_REVISION)) {
processRevision(line.substring(NEW_REVISION.length()));
}
}
private File createFile(String fileName) {
return new File(localPath, fileName);
}
private void processUnknownFile(String line) {
commitInformation = new CommitInformation();
commitInformation.setType(CommitInformation.UNKNOWN);
int index = line.indexOf('\'');
String fileName = line.substring(0, index).trim();
commitInformation.setFile(createFile(fileName));
outputDone();
}
private void processToAddFile(String line) {
commitInformation = new CommitInformation();
commitInformation.setType(CommitInformation.TO_ADD);
String fileName = line.trim();
if (fileName.endsWith(";")) { //NOI18N
fileName = fileName.substring(0, fileName.length() - 2);
}
commitInformation.setFile(createFile(fileName));
outputDone();
}
private void processFile(String filename) {
if (commitInformation == null) {
commitInformation = new CommitInformation();
}
if (filename.startsWith("no file")) { //NOI18N
filename = filename.substring(8);
}
commitInformation.setFile(createFile(filename));
}
private void processFile(File file) {
if (commitInformation == null) {
commitInformation = new CommitInformation();
}
commitInformation.setFile(file);
}
private void processRevision(String revision) {
int index = revision.indexOf(';');
if (index >= 0) {
revision = revision.substring(0, index);
}
revision = revision.trim();
if (DELETED_REVISION.equals(revision)) {
commitInformation.setType(CommitInformation.REMOVED);
}
commitInformation.setRevision(revision);
}
public void parseEnhancedMessage(String key, Object value) {
}
private File findFile(String fileName, String reposPath) {
File dir = new File(localPath);
// happens when adding a new file to a branch
if (reposPath.endsWith("/Attic")) {
reposPath = reposPath.substring(0, reposPath.length() - 6);
}
// use quick finder and fallback to original algorithm just in case
File file = quickFindFile(dir, fileName, reposPath);
if (file != null) return file;
return findFile(dir, fileName, reposPath);
}
private File findFile(File dir, String fileName, String reposPath) {
if (isWorkForRepository(dir, reposPath)) {
return new File(dir, fileName);
} else {
File file = null;
File[] subFiles = dir.listFiles();
if (subFiles != null) {
for (int i = 0; i < subFiles.length; i++) {
if (subFiles[i].isDirectory()) {
file = findFile(subFiles[i], fileName, reposPath);
if (file != null) break;
}
}
}
return file;
}
}
private File quickFindFile(File dir, String fileName, String reposPath) {
for (;;) {
File deepDir = new File(dir, reposPath);
if (isWorkForRepository(deepDir, reposPath)) {
return new File(deepDir, fileName);
}
dir = dir.getParentFile();
if (dir == null) return null;
}
}
private boolean isWorkForRepository(File dir, String reposPath) {
try {
String repository = eventManager.getClientServices().getRepositoryForDirectory(dir);
String root = eventManager.getClientServices().getRepository();
if (repository.startsWith(root)) repository = repository.substring(root.length() + 1);
return reposPath.equals(repository);
} catch (IOException e) {
return false;
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/commit/CommitCommand.java 0000644 0001753 0000144 00000047731 11175406777 030372 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.commit;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The command to commit any changes that have been made.
* @author Robert Greig
*/
public class CommitCommand extends BasicCommand {
/**
* The argument requests that must be added at the end.
* These argument requests indicate the files to be committed
*/
private final List argumentRequests = new LinkedList();
/**
* The log message used for the commit.
*/
private String message;
/**
* Forces the commit of the file(s) even if no changes were done.
* the standard behaviour is NOT-TO-BE recursive in this case.
*/
private boolean forceCommit;
/**
* The filename for the file that defines the message.
*/
private String logMessageFromFile;
/**
* Determines that no module program should run on the server.
*/
private boolean noModuleProgram;
/** Holds value of property toRevisionOrBranch. */
private String toRevisionOrBranch;
/**
* Construct a CommitCommand.
*/
public CommitCommand() {
resetCVSCommand();
}
/**
* Returns the commit message.
*/
public String getMessage() {
return message;
}
/**
* Sets the commit message.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Indicates whether the commit should be forced even if there are no
* changes.
*/
public boolean isForceCommit() {
return forceCommit;
}
/**
* Sets whether the commit should be forced even if there are no changes.
*/
public void setForceCommit(boolean forceCommit) {
this.forceCommit = forceCommit;
}
/**
* Adds the appropriate requests for a given directory.
* Sends a directory request followed by as many Entry and Modified requests
* as required.
* @param directory the directory to send requests for
* @throws IOException if an error occurs constructing the requests
*/
protected void addRequestsForDirectory(File directory)
throws IOException {
if (!directory.exists()) {
return;
}
// remove localPath prefix from directory. If left with
// nothing, use dot (".") in the directory request. Also remove the
// trailing slash
String dir = getRelativeToLocalPathInUnixStyle(directory);
try {
String repository = clientServices.getRepositoryForDirectory(
directory.getAbsolutePath());
requests.add(new DirectoryRequest(dir, repository));
String tag = clientServices.getStickyTagForDirectory(directory);
if (tag != null) {
requests.add(new StickyRequest(tag));
}
}
catch (IOException ex) {
System.err.println("An error occurred reading the respository " +
"for the directory " + dir + ": " + ex);
ex.printStackTrace();
}
// Obtain a set of all files known to CVS. We union
// this set with the set of files in the actual filesystem directory
// to obtain a set of files to commit (or at least attempt to commit).
Set set = clientServices.getAllFiles(directory);
// We must add the local files (and directories) because the above
// command does *not* return cvs controlled directories
final File[] files = directory.listFiles();
// get the union of the files in the directory and the files retrieved
// from the Entries file.
set.addAll(Arrays.asList(files));
List subdirectories = null;
if (isRecursive()) {
subdirectories = new LinkedList();
}
for (Iterator it = set.iterator(); it.hasNext();) {
File file = (File)it.next();
if (file.getName().equals("CVS")) { //NOI18N
continue;
}
try {
final Entry entry = clientServices.getEntry(file);
// a non-null entry means the file does exist in the
// Entries file for this directory
if (entry == null) {
continue;
}
// here file.isFile() is *not* used, because not existing
// files (removed ones) should also be sent
if (file.isFile()) {
sendEntryAndModifiedRequests(entry, file);
}
else if (isRecursive() && file.isDirectory()) {
File cvsSubDir = new File(file, "CVS"); //NOI18N
if (cvsSubDir.exists()) {
subdirectories.add(file);
}
}
}
catch (IOException ex) {
System.err.println("An error occurred getting the " +
"Entry for file " + file + ": " + ex);
ex.printStackTrace();
}
}
if (isRecursive()) {
for (Iterator it = subdirectories.iterator(); it.hasNext();) {
File subdirectory = (File)it.next();
addRequestsForDirectory(subdirectory);
}
}
}
/**
* Add the appropriate requests for a single file.
* A directory request is sent, followed by an Entry and Modified request.
* @param file the file to send requests for
* @throws IOException if an error occurs constructing the requests
*/
protected void addRequestsForFile(File file)
throws IOException {
final File parentDirectory = file.getParentFile();
// remove localPath prefix from directory. If left with
// nothing, use dot (".") in the directory request
String dir = getRelativeToLocalPathInUnixStyle(parentDirectory);
try {
// send a argument request indicating the file to update
requests.add(new DirectoryRequest(dir, clientServices.
getRepositoryForDirectory(parentDirectory.
getAbsolutePath())));
String tag = clientServices.getStickyTagForDirectory(parentDirectory);
if (tag != null) {
requests.add(new StickyRequest(tag));
}
}
catch (IOException ex) {
System.err.println("An error occurred reading the respository " +
"for the directory " + dir + ": " + ex);
ex.printStackTrace();
}
try {
final Entry entry = clientServices.getEntry(file);
// a non-null entry means the file does exist in the
// Entries file for this directory
if (entry != null) {
sendEntryAndModifiedRequests(entry, file);
}
}
catch (IOException ex) {
System.err.println("An error occurred getting the Entry " +
"for file " + file + ": " + ex);
ex.printStackTrace();
}
}
/**
* Should return true if unchanged files should not be sent to server.
* If false is returned, all files will be sent to server
* This method is used by sendEntryAndModifiedRequests
.
*/
protected boolean doesCheckFileTime() {
return !isForceCommit();
}
/**
* Execute the command.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
super.execute(client, em);
try {
// add arguments.
if (isForceCommit()) {
requests.add(1, new ArgumentRequest("-f")); //NOI18N
if (isRecursive()) {
requests.add(1, new ArgumentRequest("-R")); //NOI18N
}
}
if (isNoModuleProgram()) {
requests.add(1, new ArgumentRequest("-n")); //NOI18N
}
if (getToRevisionOrBranch() != null) {
requests.add(1, new ArgumentRequest("-r")); //NOI18N
requests.add(2, new ArgumentRequest(getToRevisionOrBranch()));
}
// build the message to send
String message = getMessage();
if (getLogMessageFromFile() != null) {
message = loadLogFile(getLogMessageFromFile());
}
if (message != null) {
message = message.trim();
}
if (message == null
|| message.length() == 0) {
message = "no message"; //NOI18N
}
addMessageRequest(message);
addRequestForWorkingDirectory(client);
requests.addAll(argumentRequests);
argumentRequests.clear(); // MK sanity check.
addArgumentRequests();
requests.add(CommandRequest.COMMIT);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
protected void addArgumentRequests() {
if (isForceCommit()) {
Iterator it = requests.iterator();
String directory = "";
List args = new LinkedList();
while (it.hasNext()) {
Object req = it.next();
if (req instanceof org.netbeans.lib.cvsclient.request.DirectoryRequest) {
org.netbeans.lib.cvsclient.request.DirectoryRequest dirReq = (org.netbeans.lib.cvsclient.request.DirectoryRequest)req;
// haven't checked but I'm almost sure that within the Argument request always the local directory is used.
directory = dirReq.getLocalDirectory();
}
else if (req instanceof org.netbeans.lib.cvsclient.request.EntryRequest) {
org.netbeans.lib.cvsclient.request.EntryRequest entReq = (org.netbeans.lib.cvsclient.request.EntryRequest)req;
String argument = null;
if (directory.length() == 0) {
argument = entReq.getEntry().getName();
}
else {
argument = directory + '/' + entReq.getEntry().getName();
}
args.add(new ArgumentRequest(argument));
}
}
it = args.iterator();
while (it.hasNext()) {
requests.add(it.next());
}
}
else {
super.addArgumentRequests();
}
}
/**
* This method returns how the command would looklike when typed on the command line.
* Example: checkout -p CvsCommand.java
* @returns [] files/dirs
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("commit "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName() + " "); //NOI18N
}
}
return toReturn.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file).
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'm') {
setMessage(optArg);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'f') {
setForceCommit(true);
}
else if (opt == 'F') {
setLogMessageFromFile(optArg);
}
else if (opt == 'r') {
setToRevisionOrBranch(optArg);
}
else if (opt == 'n') {
setNoModuleProgram(true);
}
else {
return false;
}
return true;
}
/**
* Returns a String defining which options are available for this command.
*/
public String getOptString() {
return "m:flRnF:r:"; //NOI18N
}
/**
* Method that is called while the command is being executed.
* Descendants can override this method to return a Builder instance
* that will parse the server's output and create data structures.
*/
public Builder createBuilder(EventManager eventMan) {
return new CommitBuilder(eventMan, getLocalDirectory(), clientServices.getRepository());
}
/**
* Generates the Argument/Argumentx series of requests depending
* on the number of lines in the message request.
*/
private void addMessageRequest(String message) {
requests.add(new ArgumentRequest("-m")); //NOI18N
StringTokenizer token = new StringTokenizer(message, "\n", false); //NOI18N
boolean first = true;
while (token.hasMoreTokens()) {
if (first) {
requests.add(new ArgumentRequest(token.nextToken()));
first = false;
}
else {
requests.add(new ArgumentxRequest(token.nextToken()));
}
}
}
/**
* Returns the filename for the file that defines the message.
*/
public String getLogMessageFromFile() {
return logMessageFromFile;
}
/**
* Sets the filename for the file that defines the message.
*/
public void setLogMessageFromFile(String logMessageFromFile) {
this.logMessageFromFile = logMessageFromFile;
}
/**
* Returns whether no module program should be executed on the server.
*/
public boolean isNoModuleProgram() {
return noModuleProgram;
}
/**
* Sets whether no module program should run on the server
*/
public void setNoModuleProgram(boolean noModuleProgram) {
this.noModuleProgram = noModuleProgram;
}
/** Getter for property toRevisionOrBranch.
* @return Value of property toRevisionOrBranch.
*/
public String getToRevisionOrBranch() {
return toRevisionOrBranch;
}
/** Setter for property toRevisionOrBranch.
* @param toRevisionOrBranch New value of property toRevisionOrBranch.
*/
public void setToRevisionOrBranch(String toRevBranch) {
this.toRevisionOrBranch = toRevBranch;
}
private String loadLogFile(String fileName)
throws CommandException {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n"); //NOI18N
}
}
catch (FileNotFoundException ex) {
throw new CommandException(ex,
CommandException.getLocalMessage("CommitCommand.logInfoFileNotExists", new Object[]{fileName})); //NOI18N
}
catch (IOException ex) {
throw new CommandException(ex,
CommandException.getLocalMessage("CommitCommand.errorReadingLogFile", new Object[]{fileName})); //NOI18N
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException exc) {
}
}
}
return buffer.toString();
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setMessage(null);
setRecursive(true);
setForceCommit(false);
setLogMessageFromFile(null);
setNoModuleProgram(false);
setToRevisionOrBranch(null);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name.
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer();
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (isForceCommit()) {
toReturn.append("-f "); //NOI18N
if (isRecursive()) {
toReturn.append("-R ");
}
}
if (isNoModuleProgram()) {
toReturn.append("-n "); //NOI18N
}
if (getToRevisionOrBranch() != null) {
toReturn.append("-r "); //NOI18N
toReturn.append(getToRevisionOrBranch() + " "); //NOI18N
}
if (getLogMessageFromFile() != null) {
toReturn.append("-F "); //NOI18N
toReturn.append(getLogMessageFromFile());
toReturn.append(" "); //NOI18N
}
if (getMessage() != null) {
toReturn.append("-m \""); //NOI18N
toReturn.append(getMessage());
toReturn.append("\" "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/commit/CommitInformation.java 0000644 0001753 0000144 00000006347 11175406777 031277 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.commit;
import org.netbeans.lib.cvsclient.command.*;
/**
* Describes commit information for a file. This is the result of doing a
* cvs commit command. The fields in instances of this object are populated
* by response handlers.
*
* @author Milos Kleint
*/
public class CommitInformation extends DefaultFileInfoContainer {
public static final String ADDED = "Added"; //NOI18N
public static final String REMOVED = "Removed"; //NOI18N
public static final String CHANGED = "Changed"; //NOI18N
public static final String UNKNOWN = "Unknown"; //NOI18N
public static final String TO_ADD = "To-be-added"; //NOI18N
/**
* The new revision (for "Added" and "Changed") or old revision (for "Removed").
*/
private String revision;
public CommitInformation() {
}
/** Getter for property revision.
* @return Value of property revision.
*/
public String getRevision() {
return revision;
}
/** Setter for property revision.
* @param revision New value of property revision.
*/
public void setRevision(String revision) {
this.revision = revision;
}
} netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/diff/ 0000755 0001753 0000144 00000000000 11175434236 024373 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/diff/DiffCommand.java 0000644 0001753 0000144 00000037411 11175406777 027424 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.diff;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The status command looks up the status of files in the repository
* @author Robert Greig
*/
public class DiffCommand extends BasicCommand {
/**
* The event manager to use
*/
protected EventManager eventManager;
/**
* Holds value of property beforeDate.
*/
private String beforeDate1;
/**
* Holds value of property firstRevision.
*/
private String revision1;
/**
* Holds value of property secondRevision.
*/
private String revision2;
/**
* Holds value of property beforeDate2.
*/
private String beforeDate2;
/**
* Keyword substitution. The -k switch in command line cvs.
*/
private String keywordSubst;
/** Holds value of property ignoreAllWhitespace. */
private boolean ignoreAllWhitespace;
/** Holds value of property ignoreBlankLines. */
private boolean ignoreBlankLines;
/** Holds value of property ignoreCase. */
private boolean ignoreCase;
/** Holds value of property ignoreSpaceChange. */
private boolean ignoreSpaceChange;
/** Holds value of property contextDiff. */
private boolean contextDiff;
/** Holds value of property unifiedDiff. */
private boolean unifiedDiff;
/**
* Construct a new diff command
*/
public DiffCommand() {
}
/**
* Create a builder for this command.
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventMan) {
if (isContextDiff() || isUnifiedDiff()) {
return null;
}
return new SimpleDiffBuilder(eventMan, this);
}
/**
* Execute a command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests.
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
eventManager = em;
super.execute(client, em);
try {
// parameters come now..
addRDSwitches();
if (getKeywordSubst() != null && !getKeywordSubst().equals("")) { //NOI18N
requests.add(new ArgumentRequest("-k" + getKeywordSubst())); //NOI18N
}
addArgumentRequest(isIgnoreAllWhitespace(), "-w"); //NOI18N
addArgumentRequest(isIgnoreBlankLines(), "-B"); //NOI18N
addArgumentRequest(isIgnoreSpaceChange(), "-b"); //NOI18N
addArgumentRequest(isIgnoreCase(), "-i"); //NOI18N
addArgumentRequest(isContextDiff(), "-c"); //NOI18N
addArgumentRequest(isUnifiedDiff(), "-u"); //NOI18N
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.DIFF);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* includes the logic of setting the -r and -D switches to the diff command
*/
private void addRDSwitches() {
if (getRevision2() != null) {
requests.add(1, new ArgumentRequest("-r")); //NOI18N
requests.add(2, new ArgumentRequest(getRevision2()));
}
else {
if (getBeforeDate2() != null) {
requests.add(1, new ArgumentRequest("-D " + getBeforeDate2())); //NOI18N
}
}
// -r switch has precendence over the -d switch - is that right??
if (getRevision1() != null) {
requests.add(1, new ArgumentRequest("-r")); //NOI18N
requests.add(2, new ArgumentRequest(getRevision1()));
}
else {
if (getBeforeDate1() != null) {
requests.add(1, new ArgumentRequest("-D " + getBeforeDate1())); //NOI18N
}
else {
// when neither revision nor flag is set for the command, it is assumed
// that the second parameters are not set either..
return;
}
}
}
/** called when server responses with "ok" or "error", (when the command finishes)
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/** Getter for property beforeDate.
* @return Value of property beforeDate.
*/
public String getBeforeDate1() {
return beforeDate1;
}
/** Setter for property beforeDate.
* @param beforeDate New value of property beforeDate.
*/
public void setBeforeDate1(String beforeDate) {
this.beforeDate1 = beforeDate;
}
/** Getter for property firstRevision.
* @return Value of property firstRevision.
*/
public String getRevision1() {
return revision1;
}
/** Setter for property firstRevision.
* @param firstRevision New value of property firstRevision.
*/
public void setRevision1(String firstRevision) {
revision1 = firstRevision;
}
/** Getter for property secondRevision.
* @return Value of property secondRevision.
*/
public String getRevision2() {
return revision2;
}
/** Setter for property secondRevision.
* @param secondRevision New value of property secondRevision.
*/
public void setRevision2(String secondRevision) {
this.revision2 = secondRevision;
}
/** Getter for property beforeDate2.
* @return Value of property beforeDate2.
*/
public String getBeforeDate2() {
return beforeDate2;
}
/** Setter for property beforeDate2.
* @param beforeDate2 New value of property beforeDate2.
*/
public void setBeforeDate2(String beforeDate2) {
this.beforeDate2 = beforeDate2;
}
/**
* Getter for property keywordSubst.
* @return Value of property keywordSubst.
*/
public String getKeywordSubst() {
return keywordSubst;
}
/**
* Setter for property keywordSubst.
* @param keywordSubst New value of property keywordSubst.
*/
public void setKeywordSubst(String keywordSubst) {
this.keywordSubst = keywordSubst;
}
/** This method returns how the command would looklike when typed on the command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("diff "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName() + " "); //NOI18N
}
}
return toReturn.toString();
}
/** takes the arguments and sets the command. To be mainly
* used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'r') {
if (getRevision1() == null) {
setRevision1(optArg);
}
else {
setRevision2(optArg);
}
}
else if (opt == 'D') {
if (getBeforeDate1() == null) {
setBeforeDate1(optArg);
}
else {
setBeforeDate2(optArg);
}
}
else if (opt == 'k') {
setKeywordSubst(optArg);
}
else if (opt == 'w') {
setIgnoreAllWhitespace(true);
}
else if (opt == 'b') {
setIgnoreSpaceChange(true);
}
else if (opt == 'B') {
setIgnoreBlankLines(true);
}
else if (opt == 'i') {
setIgnoreCase(true);
}
else if (opt == 'c') {
setContextDiff(true);
}
else if (opt == 'u') {
setUnifiedDiff(true);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "Rlr:D:k:wBbicu"; //NOI18N
}
/**
* resets all switches in the command. After calling this method,
* the command should have no switches defined and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setRevision1(null);
setRevision2(null);
setBeforeDate1(null);
setBeforeDate2(null);
setKeywordSubst(null);
setIgnoreAllWhitespace(false);
setIgnoreBlankLines(false);
setIgnoreCase(false);
setIgnoreSpaceChange(false);
setContextDiff(false);
setUnifiedDiff(false);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (getKeywordSubst() != null && getKeywordSubst().length() > 0) {
toReturn.append("-k" + getKeywordSubst() + " "); //NOI18N
}
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (getRevision1() != null) {
toReturn.append("-r " + getRevision1() + " "); //NOI18N
}
if (getBeforeDate1() != null) {
toReturn.append("-D " + getBeforeDate1() + " "); //NOI18N
}
if (getRevision2() != null) {
toReturn.append("-r " + getRevision2() + " "); //NOI18N
}
if (getBeforeDate2() != null) {
toReturn.append("-D " + getBeforeDate2() + " "); //NOI18N
}
if (isIgnoreAllWhitespace()) {
toReturn.append("-w "); //NOI18N
}
if (isIgnoreBlankLines()) {
toReturn.append("-B "); //NOI18N
}
if (isIgnoreCase()) {
toReturn.append("-i "); //NOI18N
}
if (isIgnoreSpaceChange()) {
toReturn.append("-b "); //NOI18N
}
if (isContextDiff()) {
toReturn.append("-c ");//NOI18N
}
if (isUnifiedDiff()) {
toReturn.append("-u ");//NOI18N
}
return toReturn.toString();
}
/** true if all the whitespace differences should be ignored. (-w)
* @return Value of property ignoreAllWhitespace.
*/
public boolean isIgnoreAllWhitespace() {
return this.ignoreAllWhitespace;
}
/** Setter for property ignoreAllWhitespace.
* true if all the whitespace differences should be ignored. (-w)
* @param ignoreAllWhitespace New value of property ignoreAllWhitespace.
*/
public void setIgnoreAllWhitespace(boolean ignoreAllWhitespace) {
this.ignoreAllWhitespace = ignoreAllWhitespace;
}
/** Getter for property ignoreBlankLines.
* @return Value of property ignoreBlankLines.
*/
public boolean isIgnoreBlankLines() {
return this.ignoreBlankLines;
}
/** Setter for property ignoreBlankLines.
* @param ignoreBlankLines New value of property ignoreBlankLines.
*/
public void setIgnoreBlankLines(boolean ignoreBlankLines) {
this.ignoreBlankLines = ignoreBlankLines;
}
/** Getter for property ignoreCase.
* @return Value of property ignoreCase.
*/
public boolean isIgnoreCase() {
return this.ignoreCase;
}
/** Setter for property ignoreCase.
* @param ignoreCase New value of property ignoreCase.
*/
public void setIgnoreCase(boolean ignoreCase) {
this.ignoreCase = ignoreCase;
}
/** Getter for property ignoreSpaceChange.
* @return Value of property ignoreSpaceChange.
*/
public boolean isIgnoreSpaceChange() {
return this.ignoreSpaceChange;
}
/** Setter for property ignoreSpaceChange.
* @param ignoreSpaceChange New value of property ignoreSpaceChange.
*/
public void setIgnoreSpaceChange(boolean ignoreSpaceChange) {
this.ignoreSpaceChange = ignoreSpaceChange;
}
/**
* equals to the -c switch of cvs
* Getter for property contextDiff.
* @return Value of property contextDiff.
*/
public boolean isContextDiff() {
return this.contextDiff;
}
/**
* equals to the -c switch of cvs
* Setter for property contextDiff.
* @param contextDiff New value of property contextDiff.
*/
public void setContextDiff(boolean contextDiff) {
this.contextDiff = contextDiff;
}
/**
* equals to the -u switch of cvs
* Getter for property unifiedDiff.
* @return Value of property unifiedDiff.
*/
public boolean isUnifiedDiff() {
return this.unifiedDiff;
}
/**
* equals to the -u switch of cvs.
* Setter for property unifiedDiff.
* @param unifiedDiff New value of property unifiedDiff.
*/
public void setUnifiedDiff(boolean unifiedDiff) {
this.unifiedDiff = unifiedDiff;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/diff/DiffInformation.java 0000644 0001753 0000144 00000020257 11175406777 030333 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.diff;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
/**
* Describes diff information for 2 fversions of a file. This is the result of doing a
* cvs diff command. The fields in instances of this object are populated
* by response handlers.
* @author Milos Kleint
*/
public class DiffInformation extends FileInfoContainer {
private File file;
private String repositoryFileName;
private String rightRevision;
private String leftRevision;
private String parameters;
/**
* List of changes stored here
*/
private final List changesList = new ArrayList();
private Iterator iterator;
public DiffInformation() {
}
/**
* Getter for property file.
* @return Value of property file.
*/
public File getFile() {
return file;
}
/**
* Setter for property file.
* @param file New value of property file.
*/
public void setFile(File file) {
this.file = file;
}
/**
* Getter for property repositoryFileName.
* @return Value of property repositoryFileName.
*/
public String getRepositoryFileName() {
return repositoryFileName;
}
/**
* Setter for property repositoryFileName.
* @param repositoryRevision New value of property repositoryFileName.
*/
public void setRepositoryFileName(String repositoryFileName) {
this.repositoryFileName = repositoryFileName;
}
/**
* Return a string representation of this object. Useful for debugging.
*/
public String toString() {
StringBuffer buf = new StringBuffer(30);
buf.append("\nFile: " + ((file != null)?file.getAbsolutePath():"null")); //NOI18N
buf.append("\nRCS file: " + repositoryFileName); //NOI18N
buf.append("\nRevision: " + leftRevision); //NOI18N
if (rightRevision != null) {
buf.append("\nRevision: " + rightRevision); //NOI18N
}
buf.append("\nParameters: " + parameters); //NOI18N
// buf.append(differences.toString());
return buf.toString();
}
/** Getter for property rightRevision.
* @return Value of property rightRevision.
*/
public String getRightRevision() {
return rightRevision;
}
/** Setter for property rightRevision.
* @param rightRevision New value of property rightRevision.
*/
public void setRightRevision(String rightRevision) {
this.rightRevision = rightRevision;
}
/** Getter for property leftRevision.
* @return Value of property leftRevision.
*/
public String getLeftRevision() {
return leftRevision;
}
/** Setter for property leftRevision.
* @param leftRevision New value of property leftRevision.
*/
public void setLeftRevision(String leftRevision) {
this.leftRevision = leftRevision;
}
public String getParameters() {
return parameters;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
public DiffChange createDiffChange() {
return new DiffChange();
}
public void addChange(DiffChange change) {
changesList.add(change);
}
public DiffChange getFirstChange() {
iterator = changesList.iterator();
return getNextChange();
}
public DiffChange getNextChange() {
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return null;
}
return (DiffChange)iterator.next();
}
public class DiffChange {
public static final int ADD = 0;
public static final int DELETE = 1;
public static final int CHANGE = 2;
protected int type;
private int leftBeginning = -1;
private int leftEnd = -1;
private final List leftDiff = new ArrayList();
private int rightBeginning = -1;
private int rightEnd = -1;
private final List rightDiff = new ArrayList();
public DiffChange() {
}
public void setType(int typeChange) {
// System.out.println("type=" + typeChange);
type = typeChange;
}
public int getType() {
return type;
}
public void setLeftRange(int min, int max) {
// System.out.println("setLeftRange() min=" + min + " max=" +max);
leftBeginning = min;
leftEnd = max;
}
public void setRightRange(int min, int max) {
// System.out.println("setRightRange() min=" + min + " max=" +max);
rightBeginning = min;
rightEnd = max;
}
public int getMainBeginning() {
return rightBeginning;
}
public int getRightMin() {
return rightBeginning;
}
public int getRightMax() {
return rightEnd;
}
public int getLeftMin() {
return leftBeginning;
}
public int getLeftMax() {
return leftEnd;
}
public boolean isInRange(int number, boolean left) {
if (left) {
return (number >= leftBeginning && number <= leftEnd);
}
return (number >= rightBeginning && number <= rightEnd);
}
public String getLine(int number, boolean left) {
if (left) {
int index = number - leftBeginning;
if (index < 0 || index >= leftDiff.size()) {
return null;
}
String line = (String)leftDiff.get(index);
return line;
}
else {
int index = number - rightBeginning;
if (index < 0 || index >= rightDiff.size()) {
return null;
}
String line = (String)rightDiff.get(index);
return line;
}
}
public void appendLeftLine(String diffLine) {
leftDiff.add(diffLine);
}
public void appendRightLine(String diffLine) {
rightDiff.add(diffLine);
}
}
} netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/diff/SimpleDiffBuilder.java 0000644 0001753 0000144 00000022753 11175406777 030611 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.diff;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of a diff information object and the firing of
* events when complete objects are built.
* @author Milos Kleint
*/
public class SimpleDiffBuilder implements Builder {
/**
* The event manager to use
*/
protected EventManager eventManager;
protected DiffCommand diffCommand;
/**
* The diff object that is currently being built
*/
protected DiffInformation diffInformation;
/**
* The directory in which the file being processed lives. This is
* relative to the local directory
*/
protected String fileDirectory;
protected boolean readingDiffs = false;
private static final String UNKNOWN = ": I know nothing about"; //NOI18N
private static final String CANNOT_FIND = ": cannot find"; //NOI18N
private static final String UNKNOWN_TAG = ": tag"; //NOI18N
private static final String EXAM_DIR = ": Diffing"; //NOI18N
private static final String FILE = "Index: "; //NOI18N
private static final String RCS_FILE = "RCS file: "; //NOI18N
private static final String REVISION = "retrieving revision "; //NOI18N
private static final String PARAMETERS = "diff "; //NOI18N
private DiffInformation.DiffChange currentChange;
public SimpleDiffBuilder(EventManager eventMan, DiffCommand diffComm) {
eventManager = eventMan;
diffCommand = diffComm;
}
public void outputDone() {
if (diffInformation != null) {
if (currentChange != null) {
diffInformation.addChange(currentChange);
currentChange = null;
}
eventManager.fireCVSEvent(new FileInfoEvent(this, diffInformation));
diffInformation = null;
readingDiffs = false;
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (readingDiffs) {
if (line.startsWith(FILE)) {
outputDone();
}
else {
processDifferences(line);
return;
}
}
if (line.indexOf(UNKNOWN) >= 0) {
eventManager.fireCVSEvent(new FileInfoEvent(this, diffInformation));
diffInformation = null;
return;
}
if (line.indexOf(EXAM_DIR) >= 0) {
fileDirectory = line.substring(line.indexOf(EXAM_DIR) + EXAM_DIR.length()).trim();
return;
}
if (line.startsWith(FILE)) {
processFile(line.substring(FILE.length()));
return;
}
if (line.startsWith(RCS_FILE)) {
processRCSfile(line.substring(RCS_FILE.length()));
return;
}
if (line.startsWith(REVISION)) {
processRevision(line.substring(REVISION.length()));
return;
}
if (line.startsWith(PARAMETERS)) {
processParameters(line.substring(PARAMETERS.length()));
readingDiffs = true;
return;
}
}
/* protected void processDifferences(String line) {
diffInformation.addToDifferences(line);
}
*/
protected void processFile(String line) {
outputDone();
diffInformation = createDiffInformation();
String fileName = line.trim();
if (fileName.startsWith("no file")) { //NOI18N
fileName = fileName.substring(8);
}
diffInformation.setFile(new File(diffCommand.getLocalDirectory(),
// ((fileDirectory!=null)?fileDirectory: "") + File.separator +
fileName));
}
protected void processRCSfile(String line) {
if (diffInformation == null) {
return;
}
diffInformation.setRepositoryFileName(line.trim());
}
protected void processRevision(String line) {
if (diffInformation == null) {
return;
}
line = line.trim();
// first REVISION line is the from-file, the second is the to-file
if (diffInformation.getLeftRevision() != null) {
diffInformation.setRightRevision(line);
}
else {
diffInformation.setLeftRevision(line);
}
}
protected void processParameters(String line) {
if (diffInformation == null) {
return;
}
diffInformation.setParameters(line.trim());
}
public DiffInformation createDiffInformation() {
return new DiffInformation();
}
protected void assignType(DiffInformation.DiffChange change, String line) {
int index = 0;
int cIndex = line.indexOf('c');
if (cIndex > 0) {
// change type of change
change.setType(DiffInformation.DiffChange.CHANGE);
index = cIndex;
}
else {
int aIndex = line.indexOf('a');
if (aIndex > 0) {
// add type of change
change.setType(DiffInformation.DiffChange.ADD);
index = aIndex;
}
else {
int dIndex = line.indexOf('d');
if (dIndex > 0) {
// delete type of change
change.setType(DiffInformation.DiffChange.DELETE);
index = dIndex;
}
}
}
String left = line.substring(0, index);
// System.out.println("left part of change=" + left);
change.setLeftRange(getMin(left), getMax(left));
String right = line.substring(index + 1);
// System.out.println("right part of change=" + right);
change.setRightRange(getMin(right), getMax(right));
}
private int getMin(String line) {
String nums = line;
int commaIndex = nums.indexOf(',');
if (commaIndex > 0) {
nums = nums.substring(0, commaIndex);
}
int min;
try {
min = Integer.parseInt(nums);
}
catch (NumberFormatException exc) {
min = 0;
}
// System.out.println("Min=" + min);
return min;
}
private int getMax(String line) {
String nums = line;
int commaIndex = nums.indexOf(',');
if (commaIndex > 0) {
nums = nums.substring(commaIndex + 1);
}
int max;
try {
max = Integer.parseInt(nums);
}
catch (NumberFormatException exc) {
max = 0;
}
// System.out.println("Max=" + max);
return max;
}
protected void processDifferences(String line) {
char firstChar = line.charAt(0);
if (firstChar >= '0' && firstChar <= '9') {
// we got a new difference here
// System.out.println("new Change=" + line);
if (currentChange != null) {
diffInformation.addChange(currentChange);
}
currentChange = diffInformation.createDiffChange();
assignType(currentChange, line);
}
if (firstChar == '<') {
// System.out.println("Left line=" + line);
currentChange.appendLeftLine(line.substring(2));
}
if (firstChar == '>') {
// System.out.println("right line=" + line);
currentChange.appendRightLine(line.substring(2));
}
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/edit/ 0000755 0001753 0000144 00000000000 11175434236 024410 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/edit/EditCommand.java 0000644 0001753 0000144 00000025065 11175406777 027460 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.edit;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.file.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* @author Thomas Singer
*/
public class EditCommand extends BasicCommand {
/**
* Returns the file used for backup the specified file in the edit command.
*/
public static File getEditBackupFile(File file) {
return new File(file.getParent(),
"CVS/Base/" + file.getName()); // NOI18N
}
private boolean checkThatUnedited;
private boolean forceEvenIfEdited;
private Watch temporaryWatch;
private transient ClientServices clientServices;
/**
* Construct a new editors command.
*/
public EditCommand() {
resetCVSCommand();
}
/**
* Executes this command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests.
*/
public void execute(ClientServices clientServices, EventManager eventManager)
throws CommandException {
this.clientServices = clientServices;
try {
clientServices.ensureConnection();
super.execute(clientServices, eventManager);
addArgumentRequest(isCheckThatUnedited(), "-c"); // NOI18N
addArgumentRequest(isForceEvenIfEdited(), "-f"); // NOI18N
// now add the request that indicates the working directory for the
// command
addRequestForWorkingDirectory(clientServices);
addRequest(CommandRequest.NOOP);
clientServices.processRequests(requests);
}
catch (AuthenticationException ex) {
//TODO: handle case, where connection wasn't possible to establish
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
throw new CommandException(ex, CommandException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
this.clientServices = null;
}
}
protected void addRequestForFile(File file, Entry entry) {
String temporaryWatch = Watch.getWatchString(getTemporaryWatch());
requests.add(new NotifyRequest(file, "E", temporaryWatch)); // NOI18N
try {
editFile(clientServices, file);
}
catch (IOException ex) {
// ignore
}
}
/**
* Called when server responses with "ok" or "error", (when the command
* finishes).
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* This method returns how the tag command would looklike when typed on the
* command line.
*/
public String getCVSCommand() {
StringBuffer cvsCommandLine = new StringBuffer("edit "); //NOI18N
cvsCommandLine.append(getCVSArguments());
appendFileArguments(cvsCommandLine);
return cvsCommandLine.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for
* this command.
*/
public String getOptString() {
return "Rl"; //NOI18N
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setCheckThatUnedited(false);
setForceEvenIfEdited(true);
setTemporaryWatch(null);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer cvsArguments = new StringBuffer();
if (!isRecursive()) {
cvsArguments.append("-l "); //NOI18N
}
return cvsArguments.toString();
}
/**
* Returns whether to check for unedited files.
*/
public boolean isCheckThatUnedited() {
return checkThatUnedited;
}
/**
* Sets whether to check for unedited files.
* This is cvs' -c option.
*/
public void setCheckThatUnedited(boolean checkThatUnedited) {
this.checkThatUnedited = checkThatUnedited;
}
/**
* Returns whether the edit is forces even if the files are edited.
*/
public boolean isForceEvenIfEdited() {
return forceEvenIfEdited;
}
/**
* Sets whether the edit is forces even if the files are edited.
* This is cvs' -f option.
*/
public void setForceEvenIfEdited(boolean forceEvenIfEdited) {
this.forceEvenIfEdited = forceEvenIfEdited;
}
/**
* Returns the temporary watch.
*/
public Watch getTemporaryWatch() {
return temporaryWatch;
}
/**
* Sets the temporary watch.
* This is cvs' -a option.
*/
public void setTemporaryWatch(Watch temporaryWatch) {
this.temporaryWatch = temporaryWatch;
}
private void editFile(ClientServices clientServices, File file) throws IOException {
addBaserevEntry(clientServices, file);
FileUtils.copyFile(file, EditCommand.getEditBackupFile(file));
FileUtils.setFileReadOnly(file, false);
}
/**
* Create file CVS/Baserev with entries like
* BEntry.java/1.2/
*/
private void addBaserevEntry(ClientServices clientServices, File file) throws IOException {
final Entry entry = clientServices.getEntry(file);
if (entry == null || entry.getRevision() == null || entry.isNewUserFile() || entry.isUserFileToBeRemoved()) {
throw new IllegalArgumentException("File does not have an Entry or Entry is invalid!"); // NOI18N
}
File baserevFile = new File(file.getParentFile(), "CVS/Baserev"); // NOI18N
File backupFile = new File(baserevFile.getAbsolutePath() + '~');
BufferedReader reader = null;
BufferedWriter writer = null;
boolean append = true;
boolean writeFailed = true;
final String entryStart = 'B' + file.getName() + '/';
try {
writer = new BufferedWriter(new FileWriter(backupFile));
writeFailed = false;
reader = new BufferedReader(new FileReader(baserevFile));
for (String line = reader.readLine();
line != null;
line = reader.readLine()) {
if (line.startsWith(entryStart)) {
append = false;
}
writeFailed = true;
writer.write(line);
writer.newLine();
writeFailed = false;
}
}
catch (IOException ex) {
if (writeFailed) {
throw ex;
}
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ex) {
// ignore
}
}
if (writer != null) {
try {
if (append && !writeFailed) {
writer.write(entryStart + entry.getRevision() + '/');
writer.newLine();
}
} finally {
try {
writer.close();
}
catch (IOException ex) {
// ignore
}
}
}
}
baserevFile.delete();
backupFile.renameTo(baserevFile);
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/editors/ 0000755 0001753 0000144 00000000000 11175434236 025134 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/editors/EditorsBuilder.java 0000644 0001753 0000144 00000014505 11175406777 030735 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.editors;
import java.io.*;
import java.text.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* @author Thomas Singer
* @version Nov 11, 2001
*/
public class EditorsBuilder
implements Builder {
// Constants ==============================================================
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd hh:mm:ss yyyy");
// private static final DateFormat DATE_FORMAT = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy zzz");
// Fields =================================================================
private final EventManager eventManager;
private String editorsFileName;
// Setup ==================================================================
EditorsBuilder(EventManager eventManager) {
this.editorsFileName=null;
this.eventManager = eventManager;
}
// Implemented ============================================================
public void parseLine(String line, boolean isErrorMessage) {
if (!isErrorMessage) {
parseLine(line);
}
}
public void parseEnhancedMessage(String key, Object value) {
}
public void outputDone() {
}
// Utils ==================================================================
private boolean parseLine(String line) {
StringTokenizer tokenizer = new StringTokenizer(line, "\t");
if (!tokenizer.hasMoreTokens()) {
return false;
}
//check whether line is the first editors line for this file.
//persist for later lines.
if(!line.startsWith("\t")) {
editorsFileName = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
return false;
}
}
//must have a filename associated with the line,
// either from this line or a previous one
else if(editorsFileName==null) {
return false;
}
final String user = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
return false;
}
final String dateString = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
return false;
}
final String clientName = tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) {
return false;
}
final String localDirectory = tokenizer.nextToken();
try {
FileInfoContainer fileInfoContainer = parseEntries(localDirectory,
editorsFileName,
user,
dateString,
clientName);
final CVSEvent event = new FileInfoEvent(this, fileInfoContainer);
eventManager.fireCVSEvent(event);
return true;
}
catch (ParseException ex) {
return false;
}
}
private EditorsFileInfoContainer parseEntries(String localDirectory,
String fileName,
String user,
String dateString,
String clientName) throws ParseException {
int lastSlashIndex = fileName.lastIndexOf('/');
if (lastSlashIndex >= 0) {
fileName = fileName.substring(lastSlashIndex + 1);
}
final Date date = parseDate(dateString);
final File file = new File(localDirectory, fileName);
return new EditorsFileInfoContainer(file,
user,
date,
clientName);
}
private Date parseDate(String dateString) throws ParseException {
int firstSpaceIndex = Math.max(dateString.indexOf(' '), 0);
int lastSpaceIndex = Math.min(dateString.lastIndexOf(' '), dateString.length());
// dateString = dateString.substring(0, lastSpaceIndex).trim();
dateString = dateString.substring(firstSpaceIndex, lastSpaceIndex).trim();
return DATE_FORMAT.parse(dateString);
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/editors/EditorsCommand.java 0000644 0001753 0000144 00000013713 11175406777 030725 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.editors;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* @author Thomas Singer
*/
public class EditorsCommand extends BasicCommand {
/**
* Construct a new editors command.
*/
public EditorsCommand() {
resetCVSCommand();
}
/**
* Creates the EditorsBuilder.
* @param eventManager the event manager used to received cvs events
*/
public Builder createBuilder(EventManager eventManager) {
return new EditorsBuilder(eventManager);
}
/**
* Execute the command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests.
*/
public void execute(ClientServices clientServices, EventManager eventManager)
throws CommandException, AuthenticationException {
clientServices.ensureConnection();
super.execute(clientServices, eventManager);
try {
addRequestForWorkingDirectory(clientServices);
addArgumentRequests();
addRequest(CommandRequest.EDITORS);
clientServices.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
throw new CommandException(ex, CommandException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* Called when server responses with "ok" or "error", (when the command
* finishes).
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* This method returns how the tag command would looklike when typed on the
* command line.
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("editors "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for
* this command.
*/
public String getOptString() {
return "Rl"; //NOI18N
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer();
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/editors/EditorsFileInfoContainer.java 0000644 0001753 0000144 00000005625 11175406777 032710 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.editors;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
/**
* Data object created by parsing the output of the Editors command.
* @author Thomas Singer
*/
public class EditorsFileInfoContainer extends FileInfoContainer {
private final String client;
private final Date date;
private final File file;
private final String user;
EditorsFileInfoContainer(File file, String user, Date date, String client) {
this.file = file;
this.user = user;
this.date = date;
this.client = client;
}
public File getFile() {
return file;
}
public String getClient() {
return client;
}
public Date getDate() {
return date;
}
public String getUser() {
return user;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/export/ 0000755 0001753 0000144 00000000000 11175434236 025004 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/export/ExportBuilder.java 0000644 0001753 0000144 00000007532 11175406777 030457 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.export;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* @author Milos Kleint
*/
public class ExportBuilder implements Builder {
private static final String FILE_INFOS = "MUARC?"; //NOI18N
private final EventManager eventManager;
private final String localPath;
private DefaultFileInfoContainer fileInfoContainer;
public ExportBuilder(EventManager eventManager, ExportCommand exportCommand) {
this.eventManager = eventManager;
this.localPath = exportCommand.getLocalDirectory();
}
public void outputDone() {
if (fileInfoContainer == null) {
return;
}
FileInfoEvent event = new FileInfoEvent(this, fileInfoContainer);
eventManager.fireCVSEvent(event);
fileInfoContainer = null;
}
public void parseLine(String line, boolean isErrorMessage) {
if (line.length() > 2 && line.charAt(1) == ' ') {
String firstChar = line.substring(0, 1);
if (FILE_INFOS.indexOf(firstChar) >= 0) {
String filename = line.substring(2).trim();
processFile(firstChar, filename);
}
else {
error(line);
}
}
}
public void parseEnhancedMessage(String key, Object value) {
}
private void error(String line) {
System.err.println("Don't know anything about: " + line);
}
private void processFile(String type, String filename) {
outputDone();
File file = new File(localPath, filename);
fileInfoContainer = new DefaultFileInfoContainer();
fileInfoContainer.setType(type);
fileInfoContainer.setFile(file);
outputDone();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/export/ExportCommand.java 0000644 0001753 0000144 00000042261 11175406777 030445 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.export;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The export command exports the projects (modules in the repository)
* to the local directory structure.
*
* @author MIlos Kleint
*/
public class ExportCommand extends RepositoryCommand {
private final String UPDATING = ": Updating "; // NOI18N
/**
* A store of potentially empty directories. When a directory has a file
* in it, it is removed from this set. This set allows the prune option
* to be implemented.
*/
private final Set emptyDirectories = new HashSet();
private boolean pruneDirectories;
private KeywordSubstitutionOptions keywordSubstitutionOptions;
/** Holds value of property exportByDate. */
private String exportByDate;
/** Holds value of property exportByRevision. */
private String exportByRevision;
/** Holds value of property exportDirectory. */
private String exportDirectory;
/** Holds value of property useHeadIfNotFound. */
private boolean useHeadIfNotFound;
/** Don't shorten module paths if -d specified. */
private boolean notShortenPaths;
/** Do not run module program (if any). */
private boolean notRunModuleProgram;
public ExportCommand() {
resetCVSCommand();
}
/**
* Returns the keyword substitution option.
*/
public KeywordSubstitutionOptions getKeywordSubstitutionOptions() {
return keywordSubstitutionOptions;
}
/**
* Sets the keywords substitution option.
*/
public void setKeywordSubstitutionOptions(KeywordSubstitutionOptions keywordSubstitutionOptions) {
this.keywordSubstitutionOptions = keywordSubstitutionOptions;
}
/**
* Set whether to prune directories.
* This is the -P option in the command-line CVS.
*/
public void setPruneDirectories(boolean pruneDirectories) {
this.pruneDirectories = pruneDirectories;
}
/**
* Get whether to prune directories.
* @return true if directories should be removed if they contain no files,
* false otherwise.
*/
public boolean isPruneDirectories() {
return pruneDirectories;
}
/**
* Execute this command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
protected void postExpansionExecute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
//
// moved modules code to the end of the other arguments --GAR
//
final int FIRST_INDEX = 0;
final int SECOND_INDEX = 1;
if (!isRecursive()) {
requests.add(FIRST_INDEX, new ArgumentRequest("-l")); //NOI18N
}
if (useHeadIfNotFound) {
requests.add(FIRST_INDEX, new ArgumentRequest("-f")); //NOI18N
}
if (exportDirectory != null && (!exportDirectory.equals(""))) {
requests.add(FIRST_INDEX, new ArgumentRequest("-d")); //NOI18N
requests.add(SECOND_INDEX, new ArgumentRequest(getExportDirectory()));
}
if (exportByDate != null && exportByDate.length() > 0) {
requests.add(FIRST_INDEX, new ArgumentRequest("-D")); //NOI18N
requests.add(SECOND_INDEX, new ArgumentRequest(getExportByDate()));
}
if (exportByRevision != null && exportByRevision.length() > 0) {
requests.add(FIRST_INDEX, new ArgumentRequest("-r")); //NOI18N
requests.add(SECOND_INDEX, new ArgumentRequest(getExportByRevision()));
}
if (notShortenPaths) {
requests.add(FIRST_INDEX, new ArgumentRequest("-N")); //NOI18N
}
if (notRunModuleProgram) {
requests.add(FIRST_INDEX, new ArgumentRequest("-n")); //NOI18N
}
if (getKeywordSubstitutionOptions() != null) {
requests.add(new ArgumentRequest("-k" + getKeywordSubstitutionOptions())); //NOI18N
}
addArgumentRequests();
requests.add(new DirectoryRequest(".", client.getRepository())); //NOI18N
requests.add(CommandRequest.EXPORT);
try {
client.processRequests(requests);
if (pruneDirectories) {
pruneEmptyDirectories();
}
requests.clear();
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
} finally {
removeAllCVSAdminFiles();
}
}
private void removeAllCVSAdminFiles() {
File rootDirect = null;
if (getExportDirectory() != null) {
rootDirect = new File(getLocalDirectory(), getExportDirectory());
deleteCVSSubDirs(rootDirect);
}
else {
rootDirect = new File(getLocalDirectory());
Iterator mods = expandedModules.iterator();
while (mods.hasNext()) {
String mod = mods.next().toString();
File modRoot = new File(rootDirect.getAbsolutePath(), mod);
deleteCVSSubDirs(modRoot);
}
}
}
private void deleteCVSSubDirs(File root) {
if (root.isDirectory()) {
File[] subDirs = root.listFiles();
if (subDirs == null) {
return;
}
for (int i = 0; i < subDirs.length; i++) {
if (subDirs[i].isDirectory()) {
if (subDirs[i].getName().equalsIgnoreCase("CVS")) { //NOI18N
final File[] adminFiles = subDirs[i].listFiles();
for (int j = 0; j < adminFiles.length; j++) {
adminFiles[j].delete();
}
subDirs[i].delete();
}
else {
deleteCVSSubDirs(subDirs[i]);
}
}
}
}
}
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("export "); //NOI18N
toReturn.append(getCVSArguments());
if (modules != null && modules.size() > 0) {
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
toReturn.append(module);
toReturn.append(' ');
}
}
else {
String localizedMsg = CommandException.getLocalMessage("ExportCommand.moduleEmpty.text"); //NOI18N
toReturn.append(" "); //NOI18N
toReturn.append(localizedMsg);
}
return toReturn.toString();
}
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (isUseHeadIfNotFound()) {
toReturn.append("-f "); //NOI18N
}
if (getExportByDate() != null) {
toReturn.append("-D "); //NOI18N
toReturn.append(getExportByDate());
toReturn.append(" "); //NOI18N
}
if (getExportByRevision() != null) {
toReturn.append("-r "); //NOI18N
toReturn.append(getExportByRevision());
toReturn.append(" "); //NOI18N
}
if (isPruneDirectories()) {
toReturn.append("-P "); //NOI18N
}
if (isNotShortenPaths()) {
toReturn.append("-N "); // NOI18N
}
if (isNotRunModuleProgram()) {
toReturn.append("-n "); // NOI18N
}
if (getExportDirectory() != null) {
toReturn.append("-d "); //NOI18N
toReturn.append(getExportDirectory());
toReturn.append(" "); //NOI18N
}
if (getKeywordSubstitutionOptions() != null) {
toReturn.append("-k"); //NOI18N
toReturn.append(getKeywordSubstitutionOptions().toString());
toReturn.append(" "); //NOI18N
}
return toReturn.toString();
}
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'k') {
setKeywordSubstitutionOptions(KeywordSubstitutionOptions.findKeywordSubstOption(optArg));
}
else if (opt == 'r') {
setExportByRevision(optArg);
}
else if (opt == 'f') {
setUseHeadIfNotFound(true);
}
else if (opt == 'D') {
setExportByDate(optArg);
}
else if (opt == 'd') {
setExportDirectory(optArg);
}
else if (opt == 'P') {
setPruneDirectories(true);
}
else if (opt == 'N') {
setNotShortenPaths(true);
}
else if (opt == 'n') {
setNotRunModuleProgram(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'R') {
setRecursive(true);
}
else {
return false;
}
return true;
}
public void resetCVSCommand() {
setModules(null);
setKeywordSubstitutionOptions(null);
setPruneDirectories(false);
setRecursive(true);
setExportByDate(null);
setExportByRevision(null);
setExportDirectory(null);
setUseHeadIfNotFound(false);
setNotShortenPaths(false);
setNotRunModuleProgram(false);
}
public String getOptString() {
return "k:r:D:NPlRnd:f"; //NOI18N
}
/**
* Creates the ExportBuilder.
*/
public Builder createBuilder(EventManager eventManager) {
return new ExportBuilder(eventManager, this);
}
/**
* Called when the server wants to send a message to be displayed to
* the user. The message is only for information purposes and clients
* can choose to ignore these messages if they wish.
* @param e the event
*/
public void messageSent(MessageEvent e) {
super.messageSent(e);
// we use this event to determine which directories need to be checked
// for updating
if (pruneDirectories && e.getMessage().indexOf(UPDATING) > 0) {
File file = new File(getLocalDirectory(), e.getMessage().substring(e.getMessage().indexOf(UPDATING) + UPDATING.length()));
emptyDirectories.add(file);
}
}
/**
* Prunes a directory, recursively pruning its subdirectories
* @param directory the directory to prune
*/
private boolean pruneEmptyDirectory(File directory) throws IOException {
boolean empty = true;
final File[] contents = directory.listFiles();
// should never be null, but just in case...
if (contents != null) {
for (int i = 0; i < contents.length; i++) {
if (contents[i].isFile()) {
empty = false;
}
else {
if (!contents[i].getName().equals("CVS")) { //NOI18N
empty = pruneEmptyDirectory(contents[i]);
}
}
if (!empty) {
break;
}
}
if (empty) {
// check this is a CVS directory and not some directory the user
// has stupidly called CVS...
final File entriesFile = new File(directory, "CVS/Entries"); //NOI18N
if (entriesFile.exists()) {
final File adminDir = new File(directory, "CVS"); //NOI18N
final File[] adminFiles = adminDir.listFiles();
for (int i = 0; i < adminFiles.length; i++) {
adminFiles[i].delete();
}
adminDir.delete();
directory.delete();
}
}
}
return empty;
}
/**
* Remove any directories that don't contain any files
*/
private void pruneEmptyDirectories() throws IOException {
final Iterator it = emptyDirectories.iterator();
while (it.hasNext()) {
final File dir = (File)it.next();
// we might have deleted it already (due to recursive delete)
// so we need to check existence
if (dir.exists()) {
pruneEmptyDirectory(dir);
}
}
emptyDirectories.clear();
}
/** Getter for property exportByDate.
* @return Value of property exportByDate.
*/
public String getExportByDate() {
return this.exportByDate;
}
/** Setter for property exportByDate.
* @param exportByDate New value of property exportByDate.
*/
public void setExportByDate(String exportByDate) {
this.exportByDate = exportByDate;
}
/** Getter for property exportByRevision.
* @return Value of property exportByRevision.
*/
public String getExportByRevision() {
return this.exportByRevision;
}
/** Setter for property exportByRevision.
* @param exportByRevision New value of property exportByRevision.
*/
public void setExportByRevision(String exportByRevision) {
this.exportByRevision = exportByRevision;
}
/** Getter for property exportDirectory.
* @return Value of property exportDirectory.
*/
public String getExportDirectory() {
return this.exportDirectory;
}
/** Setter for property exportDirectory.
* @param exportDirectory New value of property exportDirectory.
*/
public void setExportDirectory(String exportDirectory) {
this.exportDirectory = exportDirectory;
}
/** Getter for property useHeadIfNotFound.
* @return Value of property useHeadIfNotFound.
*/
public boolean isUseHeadIfNotFound() {
return this.useHeadIfNotFound;
}
/** Setter for property useHeadIfNotFound.
* @param useHeadIfNotFound New value of property useHeadIfNotFound.
*/
public void setUseHeadIfNotFound(boolean useHeadIfNotFound) {
this.useHeadIfNotFound = useHeadIfNotFound;
}
/**
* Getter for property notShortenPaths.
* @return Value of property notShortenPaths.
*/
public boolean isNotShortenPaths() {
return notShortenPaths;
}
/**
* Setter for property notShortenPaths.
* @param notShortenPaths New value of property notShortenPaths.
*/
public void setNotShortenPaths(boolean notShortenPaths) {
this.notShortenPaths = notShortenPaths;
}
/**
* Getter for property notRunModuleProgram.
* @return Value of property notRunModuleProgram.
*/
public boolean isNotRunModuleProgram() {
return notRunModuleProgram;
}
/**
* Setter for property notRunModuleProgram.
* @param notRunModuleProgram New value of property notRunModuleProgram.
*/
public void setNotRunModuleProgram(boolean notRunModuleProgram) {
this.notRunModuleProgram = notRunModuleProgram;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/history/ 0000755 0001753 0000144 00000000000 11175434236 025164 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/history/HistoryCommand.java 0000644 0001753 0000144 00000054727 11175406777 031017 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.history;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The history command provides information history of activities in repository.
* @author Milos Kleint
*/
public class HistoryCommand extends Command {
/**
* The requests that are sent and processed.
*/
private final List requests = new LinkedList();
/**
* The event manager to use
*/
private EventManager eventManager;
/** Holds value of property forAllUsers. */
private boolean forAllUsers;
/** Holds value of property goBackToRecord. */
private String showBackToRecordContaining;
/** Holds value of property reportCommits. */
private boolean reportCommits;
/** Holds value of property sinceDate. */
private String sinceDate;
/** Holds value of property reportEverything. */
private boolean reportEverything;
/** Holds value of property lastEventOfProject. */
private boolean lastEventOfProject;
/** Holds value of property reportCheckout. */
private boolean reportCheckouts;
/** Holds value of property sinceRevision. */
private String sinceRevision;
/** Holds value of property reportTags. */
private boolean reportTags;
/** Holds value of property sinceTag. */
private String sinceTag;
/** Holds value of property forWorkingDirectory. */
private boolean forWorkingDirectory;
/** Holds value of property reportEventType. */
private String reportEventType;
/** Holds value of property timeZone. */
private String timeZone;
/** Holds value of property lastEventForFile. */
private String[] lastEventForFile;
/** Holds value of property reportOnModule. */
private String[] reportOnModule;
/** Holds value of property reportLastEventForModule. */
private String[] reportLastEventForModule;
/** Holds value of property forUsers. */
private String[] forUsers;
/**
* Construct a new history command
*/
public HistoryCommand() {
}
/**
* Create a builder for this command.
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventMan) {
return null;
}
/**
* Execute a command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests.
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
eventManager = em;
requests.clear();
super.execute(client, em);
try {
if (client.isFirstCommand()) {
requests.add(new RootRequest(client.getRepository()));
requests.add(new UseUnchangedRequest());
}
addBooleanArgument(requests, isForAllUsers(), "-a"); //NOI18N
addBooleanArgument(requests, isForWorkingDirectory(), "-w"); //NOI18N
addBooleanArgument(requests, isLastEventOfProject(), "-l"); //NOI18N
addBooleanArgument(requests, isReportCheckouts(), "-o"); //NOI18N
addBooleanArgument(requests, isReportCommits(), "-c"); //NOI18N
addBooleanArgument(requests, isReportEverything(), "-e"); //NOI18N
addBooleanArgument(requests, isReportTags(), "-T"); //NOI18N
addStringArgument(requests, getReportEventType(), "-x"); //NOI18N
addStringArgument(requests, getShowBackToRecordContaining(), "-b"); //NOI18N
addStringArgument(requests, getSinceDate(), "-D"); //NOI18N
addStringArgument(requests, getSinceRevision(), "-r"); //NOI18N
addStringArgument(requests, getSinceTag(), "-t"); //NOI18N
addStringArrayArgument(requests, getForUsers(), "-u"); //NOI18N
addStringArrayArgument(requests, getReportLastEventForModule(), "-n"); //NOI18N
addStringArrayArgument(requests, getReportOnModule(), "-m"); //NOI18N
addStringArrayArgument(requests, getLastEventForFile(), "-f"); //NOI18N
if (!isReportCheckouts() && !isReportCommits() && !isReportTags() &&
!isReportEverything() && getReportEventType() == null && getReportOnModule() == null) {
// this is the default switch if nothing else is specified.
addBooleanArgument(requests, true, "-c"); //NOI18N
}
if (getTimeZone() != null) {
addStringArgument(requests, getTimeZone(), "-z"); //NOI18N
}
else {
addStringArgument(requests, "+0000", "-z"); //NOI18N
}
requests.add(CommandRequest.HISTORY);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
private void addStringArgument(List reqList, String property, String cvsSwitch) {
if (property != null) {
reqList.add(new ArgumentRequest(cvsSwitch));
reqList.add(new ArgumentRequest(property));
}
}
private void addStringArrayArgument(List reqList, String[] property, String cvsSwitch) {
if (property != null) {
for (int i = 0; i < property.length; i++) {
reqList.add(new ArgumentRequest(cvsSwitch));
reqList.add(new ArgumentRequest(property[i]));
}
}
}
private void addBooleanArgument(List reqList, boolean property, String cvsSwitch) {
if (property == true) {
reqList.add(new ArgumentRequest(cvsSwitch));
}
}
/** called when server responses with "ok" or "error", (when the command finishes)
*/
public void commandTerminated(TerminationEvent e) {
}
/** This method returns how the command would looklike when typed on the command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("history "); //NOI18N
toReturn.append(getCVSArguments());
return toReturn.toString();
}
/** takes the arguments and sets the command. To be mainly
* used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'a') {
setForAllUsers(true);
}
else if (opt == 'b') {
setShowBackToRecordContaining(optArg);
}
else if (opt == 'c') {
setReportCommits(true);
}
else if (opt == 'D') {
setSinceDate(optArg);
}
else if (opt == 'e') {
setReportEverything(true);
}
else if (opt == 'l') {
setLastEventOfProject(true);
}
else if (opt == 'o') {
setReportCheckouts(true);
}
else if (opt == 'r') {
setSinceRevision(optArg);
}
else if (opt == 'T') {
setReportTags(true);
}
else if (opt == 't') {
setSinceTag(optArg);
}
else if (opt == 'w') {
setForWorkingDirectory(true);
}
else if (opt == 'x') {
setReportEventType(optArg);
}
else if (opt == 'z') {
setTimeZone(optArg);
}
else if (opt == 'f') {
addLastEventForFile(optArg);
}
else if (opt == 'm') {
addReportOnModule(optArg);
}
else if (opt == 'n') {
addReportLastEventForModule(optArg);
}
else if (opt == 'u') {
addForUsers(optArg);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "ab:cD:ef:lm:n:or:Tt:u:wx:z:"; //NOI18N
}
/**
* resets all switches in the command. After calling this method,
* the command should have no switches defined and should behave defaultly.
*/
public void resetCVSCommand() {
setForAllUsers(false);
setForUsers(null);
setForWorkingDirectory(false);
setLastEventForFile(null);
setLastEventOfProject(false);
setReportCheckouts(false);
setReportCommits(false);
setReportEventType(null);
setReportEverything(false);
setReportLastEventForModule(null);
setReportOnModule(null);
setReportTags(false);
setShowBackToRecordContaining(null);
setSinceDate(null);
setSinceRevision(null);
setSinceTag(null);
setTimeZone(null);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (isForAllUsers()) {
toReturn.append("-a "); //NOI18N
}
if (isForWorkingDirectory()) {
toReturn.append("-w "); //NOI18N
}
if (isLastEventOfProject()) {
toReturn.append("-l "); //NOI18N
}
if (isReportCheckouts()) {
toReturn.append("-o "); //NOI18N
}
if (isReportCommits()) {
toReturn.append("-c "); //NOI18N
}
if (isReportEverything()) {
toReturn.append("-e "); //NOI18N
}
if (isReportTags()) {
toReturn.append("-T "); //NOI18N
}
if (getForUsers() != null) {
appendArrayToSwitches(toReturn, getForUsers(), "-u "); //NOI18N
}
if (getLastEventForFile() != null) {
appendArrayToSwitches(toReturn, getLastEventForFile(), "-f "); //NOI18N
}
if (getReportEventType() != null) {
toReturn.append("-x "); //NOI18N
toReturn.append(getReportEventType());
toReturn.append(" "); //NOI18N
}
if (getReportLastEventForModule() != null) {
appendArrayToSwitches(toReturn, getReportLastEventForModule(), "-n "); //NOI18N
}
if (getReportOnModule() != null) {
appendArrayToSwitches(toReturn, getReportOnModule(), "-m "); //NOI18N
}
if (getShowBackToRecordContaining() != null) {
toReturn.append("-b "); //NOI18N
toReturn.append(getShowBackToRecordContaining());
toReturn.append(" "); //NOI18N
}
if (getSinceDate() != null) {
toReturn.append("-D "); //NOI18N
toReturn.append(getSinceDate());
toReturn.append(" "); //NOI18N
}
if (getSinceRevision() != null) {
toReturn.append("-r "); //NOI18N
toReturn.append(getSinceRevision());
toReturn.append(" "); //NOI18N
}
if (getSinceTag() != null) {
toReturn.append("-t "); //NOI18N
toReturn.append(getSinceTag());
toReturn.append(" "); //NOI18N
}
if (getTimeZone() != null) {
toReturn.append("-z "); //NOI18N
toReturn.append(getTimeZone());
toReturn.append(" "); //NOI18N
}
return toReturn.toString();
}
private void appendArrayToSwitches(StringBuffer buff, String[] arr, String cvsSwitch) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
buff.append(cvsSwitch);
buff.append(arr[i]);
buff.append(" "); //NOI18N
}
}
/** Getter for property forAllUsers. (cvs switch -a)
* @return Value of property forAllUsers.
*/
public boolean isForAllUsers() {
return this.forAllUsers;
}
/** Setter for property forAllUsers. (cvs switch -a)
* @param forAllUsers New value of property forAllUsers.
*/
public void setForAllUsers(boolean forAllUsers) {
this.forAllUsers = forAllUsers;
}
/** Getter for property goBackToRecord. (cvs switch -b)
* @return Value of property goBackToRecord.
*/
public String getShowBackToRecordContaining() {
return this.showBackToRecordContaining;
}
/** Setter for property goBackToRecord. (cvs switch -b)
* @param goBackToRecord New value of property goBackToRecord.
*/
public void setShowBackToRecordContaining(String goBackToRecord) {
this.showBackToRecordContaining = goBackToRecord;
}
/** Getter for property reportCommits. (cvs switch -c)
* @return Value of property reportCommits.
*/
public boolean isReportCommits() {
return this.reportCommits;
}
/** Setter for property reportCommits. (cvs switch -b)
* @param reportCommits New value of property reportCommits.
*/
public void setReportCommits(boolean reportCommits) {
this.reportCommits = reportCommits;
}
/** Getter for property sinceDate. (cvs switch -D)
* @return Value of property sinceDate.
*/
public String getSinceDate() {
return this.sinceDate;
}
/** Setter for property sinceDate. (cvs switch -D)
* @param sinceDate New value of property sinceDate.
*/
public void setSinceDate(String sinceDate) {
this.sinceDate = sinceDate;
}
/** Getter for property reportEverything. (cvs switch -e)
* @return Value of property reportEverything.
*/
public boolean isReportEverything() {
return this.reportEverything;
}
/** Setter for property reportEverything. (cvs switch -e)
* @param reportEverything New value of property reportEverything.
*/
public void setReportEverything(boolean reportEverything) {
this.reportEverything = reportEverything;
}
/** Getter for property lastEventOfProject. (cvs switch -l)
* @return Value of property lastEventOfProject.
*/
public boolean isLastEventOfProject() {
return this.lastEventOfProject;
}
/** Setter for property lastEventOfProject. (cvs switch -l)
* @param lastEventOfProject New value of property lastEventOfProject.
*/
public void setLastEventOfProject(boolean lastEventOfProject) {
this.lastEventOfProject = lastEventOfProject;
}
/** Getter for property reportCheckout. (cvs switch -o)
* @return Value of property reportCheckout.
*/
public boolean isReportCheckouts() {
return this.reportCheckouts;
}
/** Setter for property reportCheckout. (cvs switch -o)
* @param reportCheckout New value of property reportCheckout.
*/
public void setReportCheckouts(boolean reportCheckout) {
this.reportCheckouts = reportCheckout;
}
/** Getter for property sinceRevision. (cvs switch -r)
* @return Value of property sinceRevision.
*/
public String getSinceRevision() {
return this.sinceRevision;
}
/** Setter for property sinceRevision. (cvs switch -r)
* @param sinceRevision New value of property sinceRevision.
*/
public void setSinceRevision(String sinceRevision) {
this.sinceRevision = sinceRevision;
}
/** Getter for property reportTags. (cvs switch -T)
* @return Value of property reportTags.
*/
public boolean isReportTags() {
return this.reportTags;
}
/** Setter for property reportTags. (cvs switch -T)
* @param reportTags New value of property reportTags.
*/
public void setReportTags(boolean reportTags) {
this.reportTags = reportTags;
}
/** Getter for property sinceTag. (cvs switch -t)
* @return Value of property sinceTag.
*/
public String getSinceTag() {
return this.sinceTag;
}
/** Setter for property sinceTag. (cvs switch -t)
* @param sinceTag New value of property sinceTag.
*/
public void setSinceTag(String sinceTag) {
this.sinceTag = sinceTag;
}
/** Getter for property forWorkingDirectory. (cvs switch -w)
* @return Value of property forWorkingDirectory.
*/
public boolean isForWorkingDirectory() {
return this.forWorkingDirectory;
}
/** Setter for property forWorkingDirectory. (cvs switch -w)
* @param forWorkingDirectory New value of property forWorkingDirectory.
*/
public void setForWorkingDirectory(boolean forWorkingDirectory) {
this.forWorkingDirectory = forWorkingDirectory;
}
/** Getter for property reportEventType. (cvs switch -x)
* @return Value of property reportEventType.
*/
public String getReportEventType() {
return this.reportEventType;
}
/** Setter for property reportEventType. (cvs switch -x)
* @param reportEventType New value of property reportEventType.
*/
public void setReportEventType(String reportEventType) {
this.reportEventType = reportEventType;
}
/** Getter for property timeZone. (cvs switch -z)
* @return Value of property timeZone.
*/
public String getTimeZone() {
return this.timeZone;
}
/** Setter for property timeZone. (cvs switch -z)
* @param timeZone New value of property timeZone.
*/
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
/** Getter for property lastEventForFile. (cvs switch -f)
* @return Value of property lastEventForFile.
*/
public String[] getLastEventForFile() {
return this.lastEventForFile;
}
/** Setter for property lastEventForFile. (cvs switch -f)
* @param lastEventForFile New value of property lastEventForFile.
*/
public void setLastEventForFile(String[] lastEventForFile) {
this.lastEventForFile = lastEventForFile;
}
public void addLastEventForFile(String newFile) {
this.lastEventForFile = addNewValue(this.lastEventForFile, newFile);
}
/** Getter for property reportOnModule. (cvs switch -m)
* @return Value of property reportOnModule.
*/
public String[] getReportOnModule() {
return this.reportOnModule;
}
/** Setter for property reportOnModule. (cvs switch -m)
* @param reportOnModule New value of property reportOnModule.
*/
public void setReportOnModule(String[] reportOnModule) {
this.reportOnModule = reportOnModule;
}
public void addReportOnModule(String newReportOnModule) {
this.reportOnModule = addNewValue(this.reportOnModule, newReportOnModule);
}
/** Getter for property reportLastEventForModule. (cvs switch -n)
* @return Value of property reportLastEventForModule.
*/
public String[] getReportLastEventForModule() {
return this.reportLastEventForModule;
}
/** Setter for property reportLastEventForModule. (cvs switch -n)
* @param reportLastEventForModule New value of property reportLastEventForModule.
*/
public void setReportLastEventForModule(String[] reportLastEventForModule) {
this.reportLastEventForModule = reportLastEventForModule;
}
public void addReportLastEventForModule(String newModule) {
this.reportLastEventForModule = addNewValue(this.reportLastEventForModule, newModule);
}
/** Getter for property forUsers. (cvs switch -u)
* @return Value of property forUsers.
*/
public String[] getForUsers() {
return this.forUsers;
}
/** Setter for property forUsers. (cvs switch -u)
* @param forUsers New value of property forUsers.
*/
public void setForUsers(String[] forUsers) {
this.forUsers = forUsers;
}
public void addForUsers(String forUser) {
this.forUsers = addNewValue(this.forUsers, forUser);
}
private String[] addNewValue(String[] arr, String newVal) {
if (arr == null) {
arr = new String[]{newVal};
return arr;
}
String[] newValue = new String[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
newValue[i] = arr[i];
}
newValue[newValue.length] = newVal;
return newValue;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/importcmd/ 0000755 0001753 0000144 00000000000 11175434236 025461 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/importcmd/ImportBuilder.java 0000644 0001753 0000144 00000010245 11175406777 031120 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.importcmd;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* @author Thomas Singer
*/
public class ImportBuilder
implements Builder {
private static final String NO_CONFLICTS = "No conflicts created by this import"; //NOI18N
private static final String FILE_INFOS = "NUCIL?"; //NOI18N
private final EventManager eventManager;
private final String localPath;
private final String module;
private DefaultFileInfoContainer fileInfoContainer;
public ImportBuilder(EventManager eventManager, ImportCommand importCommand) {
this.eventManager = eventManager;
this.localPath = importCommand.getLocalDirectory();
this.module = importCommand.getModule();
}
public void outputDone() {
if (fileInfoContainer == null) {
return;
}
FileInfoEvent event = new FileInfoEvent(this, fileInfoContainer);
eventManager.fireCVSEvent(event);
fileInfoContainer = null;
}
public void parseLine(String line, boolean isErrorMessage) {
if (line.length() > 2 && line.charAt(1) == ' ') {
String firstChar = line.substring(0, 1);
if (FILE_INFOS.indexOf(firstChar) >= 0) {
String filename = line.substring(2).trim();
processFile(firstChar, filename);
}
else {
error(line);
}
}
else if (line.startsWith(NO_CONFLICTS)) {
outputDone();
}
}
public void parseEnhancedMessage(String key, Object value) {
}
private void error(String line) {
System.err.println("Don't know anything about: " + line);
}
private void processFile(String type, String filename) {
outputDone();
filename = filename.substring(module.length());
File file = new File(localPath, filename);
fileInfoContainer = new DefaultFileInfoContainer();
fileInfoContainer.setType(type);
fileInfoContainer.setFile(file);
outputDone();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/importcmd/ImportCommand.java 0000644 0001753 0000144 00000047311 11175406777 031114 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.importcmd;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
import org.netbeans.lib.cvsclient.response.WrapperSendResponse;
import org.netbeans.lib.cvsclient.util.*;
/**
* The import command imports local directory structures into the repository.
*
* @author Thomas Singer
*/
public class ImportCommand extends BuildableCommand {
private Map wrapperMap = new HashMap();
private String logMessage;
private String module;
private String releaseTag;
private String vendorBranch;
private String vendorTag;
private String importDirectory;
private KeywordSubstitutionOptions keywordSubstitutionOptions;
private boolean useFileModifTime;
private List ignoreList = new LinkedList();
public ImportCommand() {
resetCVSCommand();
}
public void addWrapper(String filenamePattern, KeywordSubstitutionOptions keywordSubstitutionOptions) {
if (keywordSubstitutionOptions == null) {
throw new IllegalArgumentException("keywordSubstitutionOptions must not be null");
}
wrapperMap.put(new SimpleStringPattern(filenamePattern), keywordSubstitutionOptions);
}
public void addWrapper(StringPattern filenamePattern, KeywordSubstitutionOptions keywordSubstitutionOptions) {
if (keywordSubstitutionOptions == null) {
throw new IllegalArgumentException("keywordSubstitutionOptions must not be null");
}
wrapperMap.put(filenamePattern, keywordSubstitutionOptions);
}
/**
* Compliant method to addWrapper. It replaces the whole list of cvswrappers.
* The Map's structure should be following:
* Key: instance of StringPattern(fileName wildpattern)
* Value: instance of KeywordSubstitutionOptions
*/
public void setWrappers(Map wrapperMap) {
this.wrapperMap = wrapperMap;
}
/**
* Returns a map with all wrappers.
* For map descriptions see setWrapper()
*/
public Map getWrappers() {
return wrapperMap;
}
/**
* Returns the keyword substitution option.
*/
public KeywordSubstitutionOptions getKeywordSubstitutionOptions() {
return keywordSubstitutionOptions;
}
/**
* Sets the keywords substitution option.
*/
public void setKeywordSubstitutionOptions(KeywordSubstitutionOptions keywordSubstitutionOptions) {
this.keywordSubstitutionOptions = keywordSubstitutionOptions;
}
/**
* Returns the release tag.
*/
public String getReleaseTag() {
return releaseTag;
}
/**
* Sets the necessary release tag.
*/
public void setReleaseTag(String releaseTag) {
this.releaseTag = getTrimmedString(releaseTag);
}
/**
* Returns the log message.
*/
public String getLogMessage() {
return logMessage;
}
/**
* Sets the log message.
*/
public void setLogMessage(String logMessage) {
this.logMessage = getTrimmedString(logMessage);
}
/**
* Returns the module (the in-repository path, where the files should be
* stored.
*/
public String getModule() {
return module;
}
/**
* Sets the module (the in-repository path, where the files should be
* stored).
*/
public void setModule(String module) {
this.module = getTrimmedString(module);
}
/**
* Pints to directoty to import.
*/
public void setImportDirectory(String directory) {
importDirectory = directory;
}
public String getImportDirectory() {
return importDirectory;
}
/**
* Returns the vendor branch.
*/
public String getVendorBranch() {
return vendorBranch;
}
/**
* Returns the vendor branch.
* If not set, then 1.1.1 is returned.
*/
private String getVendorBranchNotNull() {
if (vendorBranch == null) {
return "1.1.1"; //NOI18N
}
return vendorBranch;
}
/**
* Sets the vendor branch.
* If null is set, the default branch 1.1.1 is used automatically.
*/
public void setVendorBranch(String vendorBranch) {
this.vendorBranch = getTrimmedString(vendorBranch);
}
/**
* Returns the vendor tag.
*/
public String getVendorTag() {
return vendorTag;
}
/**
* Sets the necessary vendor tag.
*/
public void setVendorTag(String vendorTag) {
this.vendorTag = getTrimmedString(vendorTag);
}
/**
* Tells, whether the file modification time is to be used as the time of the import.
*/
public boolean isUseFileModifTime() {
return useFileModifTime;
}
/**
* Sets whether the file modification time is to be used as the time of the import.
*/
public void setUseFileModifTime(boolean useFileModifTime) {
this.useFileModifTime = useFileModifTime;
}
/**
* Get a list of files that are ignored by import.
*/
public List getIgnoreFiles() {
return Collections.unmodifiableList(ignoreList);
}
/**
* Add a file name that is to be ignored by the import.
*/
public void addIgnoredFile(String ignoredFileName) {
ignoreList.add(ignoredFileName);
}
/**
* Executes thiz command using the set options.
*/
public void execute(ClientServices client, EventManager eventManager)
throws CommandException, AuthenticationException {
// check necessary fields
if (getLogMessage() == null) {
String localizedMsg = CommandException.getLocalMessage("ImportCommand.messageEmpty"); //NOI18N
throw new CommandException("message may not be null nor empty", //NOI18N
localizedMsg);
}
if (getModule() == null) {
String localizedMsg = CommandException.getLocalMessage("ImportCommand.moduleEmpty"); //NOI18N
throw new CommandException("module may not be null nor empty", //NOI18N
localizedMsg);
}
if (getReleaseTag() == null) {
String localizedMsg = CommandException.getLocalMessage("ImportCommand.releaseTagEmpty"); //NOI18N
throw new CommandException("release tag may not be null nor empty", //NOI18N
localizedMsg);
}
if (getVendorTag() == null) {
String localizedMsg = CommandException.getLocalMessage("ImportCommand.vendorTagEmpty"); //NOI18N
throw new CommandException("vendor tag may not be null nor empty", //NOI18N
localizedMsg);
}
client.ensureConnection();
// get the connection wrappers here
Map allWrappersMap = new HashMap(client.getWrappersMap());
allWrappersMap.putAll(getWrappers());
setWrappers(allWrappersMap);
// start working
super.execute(client, eventManager);
assert getLocalDirectory() != null : "local directory may not be null";
List requestList = new ArrayList();
try {
// add requests
requestList.add(new ArgumentRequest("-b")); //NOI18N
requestList.add(new ArgumentRequest(getVendorBranchNotNull()));
if (getKeywordSubstitutionOptions() != null) {
requestList.add(new ArgumentRequest("-k")); //NOI18N
requestList.add(new ArgumentRequest(getKeywordSubstitutionOptions().toString()));
}
addMessageRequests(requestList, getLogMessage());
addWrapperRequests(requestList, this.wrapperMap);
if (isUseFileModifTime()) {
requestList.add(new ArgumentRequest("-d")); //NOI18N
}
for (int i = 0; i < ignoreList.size(); i++) {
requestList.add(new ArgumentRequest("-I")); //NOI18N
requestList.add(new ArgumentRequest((String) ignoreList.get(i)));
}
requestList.add(new ArgumentRequest(getModule()));
requestList.add(new ArgumentRequest(getVendorTag()));
requestList.add(new ArgumentRequest(getReleaseTag()));
addFileRequests(new File(getLocalDirectory()),
requestList, client);
requestList.add(new DirectoryRequest(".", getRepositoryRoot(client))); //NOI18N
requestList.add(CommandRequest.IMPORT);
// process the requests
client.processRequests(requestList);
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
String localizedMsg = CommandException.getLocalMessage("CommandException.EndOfFile", null); //NOI18N
throw new CommandException(ex, localizedMsg);
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
}
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("import "); //NOI18N
toReturn.append(getCVSArguments());
if (getModule() != null) {
toReturn.append(" "); //NOI18N
toReturn.append(getModule());
}
else {
String localizedMsg = CommandException.getLocalMessage("ImportCommand.moduleEmpty.text"); //NOI18N
toReturn.append(" "); //NOI18N
toReturn.append(localizedMsg);
}
if (getVendorTag() != null) {
toReturn.append(" "); //NOI18N
toReturn.append(getVendorTag());
}
else {
String localizedMsg = CommandException.getLocalMessage("ImportCommand.vendorTagEmpty.text"); //NOI18N
toReturn.append(" "); //NOI18N
toReturn.append(localizedMsg);
}
if (getReleaseTag() != null) {
toReturn.append(" "); //NOI18N
toReturn.append(getReleaseTag());
}
else {
String localizedMsg = CommandException.getLocalMessage("ImportCommand.releaseTagEmpty.text"); //NOI18N
toReturn.append(" "); //NOI18N
toReturn.append(localizedMsg);
}
return toReturn.toString();
}
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (getLogMessage() != null) {
toReturn.append("-m \""); //NOI18N
toReturn.append(getLogMessage());
toReturn.append("\" "); //NOI18N
}
if (getKeywordSubstitutionOptions() != null) {
toReturn.append("-k"); //NOI18N
toReturn.append(getKeywordSubstitutionOptions().toString());
toReturn.append(" "); //NOI18N
}
if (getVendorBranch() != null) {
toReturn.append("-b "); //NOI18N
toReturn.append(getVendorBranch());
toReturn.append(" "); //NOI18N
}
if (isUseFileModifTime()) {
toReturn.append("-d "); // NOI18N
}
if (wrapperMap.size() > 0) {
Iterator it = wrapperMap.keySet().iterator();
while (it.hasNext()) {
StringPattern pattern = (StringPattern)it.next();
KeywordSubstitutionOptions keywordSubstitutionOptions = (KeywordSubstitutionOptions)wrapperMap.get(pattern);
toReturn.append("-W "); //NOI18N
toReturn.append(pattern.toString());
toReturn.append(" -k '"); //NOI18N
toReturn.append(keywordSubstitutionOptions.toString());
toReturn.append("' "); //NOI18N
}
}
for (Iterator it = ignoreList.iterator(); it.hasNext(); ) {
toReturn.append("-I "); //NOI18N
toReturn.append((String) it.next());
toReturn.append(" "); //NOI18N
}
return toReturn.toString();
}
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'b') {
setVendorBranch(optArg);
}
else if (opt == 'm') {
setLogMessage(optArg);
}
else if (opt == 'k') {
setKeywordSubstitutionOptions(KeywordSubstitutionOptions.findKeywordSubstOption(optArg));
}
else if (opt == 'W') {
Map wrappers = WrapperSendResponse.parseWrappers(optArg);
for (Iterator it = wrappers.keySet().iterator(); it.hasNext(); ) {
StringPattern pattern = (StringPattern) it.next();
KeywordSubstitutionOptions keywordOption = (KeywordSubstitutionOptions) wrappers.get(pattern);
addWrapper(pattern, keywordOption);
}
}
else if (opt == 'd') {
setUseFileModifTime(true);
}
else if (opt == 'I') {
addIgnoredFile(optArg);
}
else {
return false;
}
return true;
}
public void resetCVSCommand() {
setLogMessage(null);
setModule(null);
setReleaseTag(null);
setVendorTag(null);
setVendorBranch(null);
setUseFileModifTime(false);
ignoreList.clear();
wrapperMap.clear();
}
public String getOptString() {
return "m:W:b:k:dI:"; //NOI18N
}
/**
* Adds requests for the specified logMessage to the specified requestList.
*/
private void addMessageRequests(List requestList, String logMessage) {
requestList.add(new ArgumentRequest("-m")); //NOI18N
StringTokenizer token = new StringTokenizer(logMessage, "\n", false); //NOI18N
boolean first = true;
while (token.hasMoreTokens()) {
if (first) {
requestList.add(new ArgumentRequest(token.nextToken()));
first = false;
}
else {
requestList.add(new ArgumentxRequest(token.nextToken()));
}
}
}
/**
* Adds requests for specified wrappers to the specified requestList.
*/
private void addWrapperRequests(List requestList, Map wrapperMap) {
for (Iterator it = wrapperMap.keySet().iterator(); it.hasNext();) {
StringPattern pattern = (StringPattern) it.next();
KeywordSubstitutionOptions keywordSubstitutionOptions = (KeywordSubstitutionOptions)wrapperMap.get(pattern);
StringBuffer buffer = new StringBuffer();
buffer.append(pattern.toString());
buffer.append(" -k '"); //NOI18N
buffer.append(keywordSubstitutionOptions.toString());
buffer.append("'"); //NOI18N
requestList.add(new ArgumentRequest("-W")); //NOI18N
requestList.add(new ArgumentRequest(buffer.toString()));
}
}
/**
* Adds recursively all request for files and directories in the specified
* directory to the specified requestList.
*/
private void addFileRequests(File directory,
List requestList,
ClientServices clientServices)
throws IOException {
String relativePath = getRelativeToLocalPathInUnixStyle(directory);
String repository = getRepositoryRoot(clientServices);
if (!relativePath.equals(".")) { //NOI18N
repository += '/' + relativePath;
}
requestList.add(new DirectoryRequest(relativePath, repository));
File[] files = directory.listFiles();
if (files == null) {
return;
}
List subdirectories = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
String filename = file.getName();
if (clientServices.shouldBeIgnored(directory, filename)) {
continue;
}
if (file.isDirectory()) {
if (subdirectories == null) {
subdirectories = new LinkedList();
}
subdirectories.add(file);
}
else {
boolean isBinary = isBinary(filename);
requestList.add(new ModifiedRequest(file, isBinary));
}
}
if (subdirectories != null) {
for (Iterator it = subdirectories.iterator(); it.hasNext();) {
File subdirectory = (File)it.next();
addFileRequests(subdirectory, requestList, clientServices);
}
}
}
/**
* Returns the used root path in the repository.
* It's built from the repository stored in the clientService and the
* module.
*/
private String getRepositoryRoot(ClientServices clientServices) {
String repository = clientServices.getRepository() + '/' + getModule();
return repository;
}
/**
* Returns true, if the file for the specified filename should be treated as
* a binary file.
*
* The information comes from the wrapper map and the set keywordsubstitution.
*/
private boolean isBinary(String filename) {
KeywordSubstitutionOptions keywordSubstitutionOptions = getKeywordSubstitutionOptions();
for (Iterator it = wrapperMap.keySet().iterator(); it.hasNext();) {
StringPattern pattern = (StringPattern)it.next();
if (pattern.doesMatch(filename)) {
keywordSubstitutionOptions = (KeywordSubstitutionOptions)wrapperMap.get(pattern);
break;
}
}
return keywordSubstitutionOptions == KeywordSubstitutionOptions.BINARY;
}
/**
* Creates the ImportBuilder.
*/
public Builder createBuilder(EventManager eventManager) {
return new ImportBuilder(eventManager, this);
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/log/ 0000755 0001753 0000144 00000000000 11175434236 024244 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/log/LogBuilder.java 0000644 0001753 0000144 00000032365 11175406777 027161 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.log;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* Handles the building of a log information object and the firing of
* events when complete objects are built.
* @author Milos Kleint
*/
public class LogBuilder implements Builder {
private static final String LOGGING_DIR = ": Logging "; //NOI18N
private static final String RCS_FILE = "RCS file: "; //NOI18N
private static final String WORK_FILE = "Working file: "; //NOI18N
private static final String REV_HEAD = "head: "; //NOI18N
private static final String BRANCH = "branch: "; //NOI18N
private static final String LOCKS = "locks: "; //NOI18N
private static final String ACCESS_LIST = "access list: "; //NOI18N
private static final String SYM_NAME = "symbolic names:"; //NOI18N
private static final String KEYWORD_SUBST = "keyword substitution: "; //NOI18N
private static final String TOTAL_REV = "total revisions: "; //NOI18N
private static final String SEL_REV = ";\tselected revisions: "; //NOI18N
private static final String DESCRIPTION = "description:"; //NOI18N
private static final String REVISION = "revision "; //NOI18N
private static final String DATE = "date: "; //NOI18N
private static final String BRANCHES = "branches: "; //NOI18N
private static final String AUTHOR = "author: "; //NOI18N
private static final String STATE = "state: "; //NOI18N
private static final String LINES = "lines: "; //NOI18N
private static final String COMMITID = "commitid: "; //NOI18N
private static final String SPLITTER = "----------------------------"; //NOI18N
private static final String FINAL_SPLIT = "============================================================================="; //NOI18N
private static final String ERROR = ": nothing known about "; //NOI18N
private static final String NO_FILE = "no file"; //NOI18N
/**
* The event manager to use
*/
protected EventManager eventManager;
protected BasicCommand logCommand;
/**
* The log object that is currently being built
*/
protected LogInformation logInfo;
protected LogInformation.Revision revision;
/**
* The directory in which the file being processed lives. This is
* relative to the local directory
*/
protected String fileDirectory;
private boolean addingSymNames;
private boolean addingDescription;
private boolean addingLogMessage;
private StringBuffer tempBuffer = null;
private List messageList;
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); //NOI18N
public LogBuilder(EventManager eventMan, BasicCommand command) {
logCommand = command;
eventManager = eventMan;
addingSymNames = false;
addingDescription = false;
addingLogMessage = false;
logInfo = null;
revision = null;
messageList = new ArrayList(500);
}
public void outputDone() {
if (logInfo != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, logInfo));
logInfo = null;
messageList = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (line.equals(FINAL_SPLIT)) {
if (addingDescription) {
addingDescription = false;
logInfo.setDescription(tempBuffer.toString());
}
if (addingLogMessage) {
addingLogMessage = false;
revision.setMessage(CommandUtils.findUniqueString(tempBuffer.toString(), messageList));
}
if (revision != null) {
logInfo.addRevision(revision);
revision = null;
}
// fire the event and exit
if (logInfo != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, logInfo));
logInfo = null;
tempBuffer = null;
}
return;
}
if (addingLogMessage) {
// first check for the branches tag
if (line.startsWith(BRANCHES)) {
processBranches(line.substring(BRANCHES.length()));
}
else {
processLogMessage(line);
return;
}
}
if (addingSymNames) {
processSymbolicNames(line);
}
if (addingDescription) {
processDescription(line);
}
// revision stuff first -> will be the most common to parse
if (line.startsWith(REVISION)) {
processRevisionStart(line);
}
if (line.startsWith(DATE)) {
processRevisionDate(line);
}
if (line.startsWith(KEYWORD_SUBST)) {
logInfo.setKeywordSubstitution(line.substring(KEYWORD_SUBST.length()).trim().intern());
addingSymNames = false;
return;
}
if (line.startsWith(DESCRIPTION)) {
tempBuffer = new StringBuffer(line.substring(DESCRIPTION.length()));
addingDescription = true;
}
if (line.indexOf(LOGGING_DIR) >= 0) {
fileDirectory = line.substring(line.indexOf(LOGGING_DIR) + LOGGING_DIR.length()).trim();
return;
}
if (line.startsWith(RCS_FILE)) {
processRcsFile(line.substring(RCS_FILE.length()));
return;
}
if (line.startsWith(WORK_FILE)) {
processWorkingFile(line.substring(WORK_FILE.length()));
return;
}
if (line.startsWith(REV_HEAD)) {
logInfo.setHeadRevision(line.substring(REV_HEAD.length()).trim().intern());
return;
}
if (line.startsWith(BRANCH)) {
logInfo.setBranch(line.substring(BRANCH.length()).trim().intern());
}
if (line.startsWith(LOCKS)) {
logInfo.setLocks(line.substring(LOCKS.length()).trim().intern());
}
if (line.startsWith(ACCESS_LIST)) {
logInfo.setAccessList(line.substring(ACCESS_LIST.length()).trim().intern());
}
if (line.startsWith(SYM_NAME)) {
addingSymNames = true;
}
if (line.startsWith(TOTAL_REV)) {
int ind = line.indexOf(';');
if (ind < 0) {
// no selected revisions here..
logInfo.setTotalRevisions(line.substring(TOTAL_REV.length()).trim().intern());
logInfo.setSelectedRevisions("0"); //NOI18N
}
else {
String total = line.substring(0, ind);
String select = line.substring(ind, line.length());
logInfo.setTotalRevisions(total.substring(TOTAL_REV.length()).trim().intern());
logInfo.setSelectedRevisions(select.substring(SEL_REV.length()).trim().intern());
}
}
}
private String findUniqueString(String name, List list) {
if (name == null) {
return null;
}
int index = list.indexOf(name);
if (index >= 0) {
return (String)list.get(index);
}
else {
String newName = name;
list.add(newName);
return newName;
}
}
private void processRcsFile(String line) {
if (logInfo != null) {
//do fire logcreated event;
}
logInfo = new LogInformation();
logInfo.setRepositoryFilename(line.trim());
}
private void processWorkingFile(String line) {
String fileName = line.trim();
if (fileName.startsWith(NO_FILE)) {
fileName = fileName.substring(8);
}
logInfo.setFile(createFile(line));
}
private void processBranches(String line) {
int ind = line.lastIndexOf(';');
if (ind > 0) {
line = line.substring(0, ind);
}
revision.setBranches(line.trim());
}
private void processLogMessage(String line) {
if (line.startsWith(SPLITTER)) {
addingLogMessage = false;
revision.setMessage(findUniqueString(tempBuffer.toString(), messageList));
return;
}
tempBuffer.append(line + "\n"); //NOI18N
}
private void processSymbolicNames(String line) {
if (!line.startsWith(KEYWORD_SUBST)) {
line = line.trim();
int index = line.indexOf(':');
if (index > 0) {
String symName = line.substring(0, index).trim();
String revName = line.substring(index + 1, line.length()).trim();
logInfo.addSymbolicName(symName.intern(), revName.intern());
}
}
}
private void processDescription(String line) {
if (line.startsWith(SPLITTER)) {
addingDescription = false;
logInfo.setDescription(tempBuffer.toString());
return;
}
tempBuffer.append(line);
}
private void processRevisionStart(String line) {
if (revision != null) {
logInfo.addRevision(revision);
}
revision = logInfo.createNewRevision(
line.substring(REVISION.length()).intern());
}
private void processRevisionDate(String line) {
StringTokenizer tokenizer = new StringTokenizer(line, ";", false); //NOI18N
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken().trim();
if (token.startsWith(DATE)) {
String dateString = token.substring(DATE.length());
Date date = null;
try {
// some servers use dashes to separate date components, so replace with slashes
// also add a default GMT timezone at the end, if the server already put one in this one will be ignored by the parser
dateString = dateString.replace('/', '-') + " +0000"; //NOI18N
date = dateFormat.parse(dateString);
} catch (ParseException e) {
BugLog.getInstance().bug("Couldn't parse date " + dateString); //NOI18N
}
revision.setDate(date, dateString);
}
else if (token.startsWith(AUTHOR)) revision.setAuthor(token.substring(AUTHOR.length()));
else if (token.startsWith(STATE)) revision.setState(token.substring(STATE.length()));
else if (token.startsWith(LINES)) revision.setLines(token.substring(LINES.length()));
else if (token.startsWith(COMMITID)) revision.setCommitID(token.substring(COMMITID.length()));
}
addingLogMessage = true;
tempBuffer = new StringBuffer();
}
/**
* @param fileName relative URL-path to command execution directory
*/
protected File createFile(String fileName) {
StringBuffer path = new StringBuffer();
path.append(logCommand.getLocalDirectory());
path.append(File.separator);
path.append(fileName.replace('/', File.separatorChar)); // NOI18N
return new File(path.toString());
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/log/LogCommand.java 0000644 0001753 0000144 00000032623 11175406777 027146 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.log;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The log command looks up the log(history) of file(s) in the repository
* @author Milos Kleint
*/
public class LogCommand extends BasicCommand {
/**
* The event manager to use.
*/
protected EventManager eventManager;
/**
* Holds value of property defaultBranch.
*/
private boolean defaultBranch;
/**
* Holds value of property dateFilter.
*/
private String dateFilter;
/**
* Holds value of property headerOnly.
*/
private boolean headerOnly;
/**
* Holds value of property noTags.
*/
private boolean noTags;
/**
* Holds value of property revisionFilter.
*/
private String revisionFilter;
/**
* Holds value of property stateFilter.
*/
private String stateFilter;
/**
* Holds value of property userFilter.
*/
private String userFilter;
/**
* Holds value of property headerAndDescOnly.
*/
private boolean headerAndDescOnly;
/**
* Construct a new status command
*/
public LogCommand() {
resetCVSCommand();
}
/**
* Create a builder for this command.
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventMan) {
return new LogBuilder(eventMan, this);
}
/**
* Execute a command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests.
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
eventManager = em;
super.execute(client, em);
try {
// first send out all possible parameters..
if (defaultBranch) {
requests.add(1, new ArgumentRequest("-b")); //NOI18N
}
if (headerAndDescOnly) {
requests.add(1, new ArgumentRequest("-t")); //NOI18N
}
if (headerOnly) {
requests.add(1, new ArgumentRequest("-h")); //NOI18N
}
if (noTags) {
requests.add(1, new ArgumentRequest("-N")); //NOI18N
}
if (userFilter != null) {
requests.add(1, new ArgumentRequest("-w" + userFilter)); //NOI18N
}
if (revisionFilter != null) {
requests.add(1, new ArgumentRequest("-r" + revisionFilter)); //NOI18N
}
if (stateFilter != null) {
requests.add(1, new ArgumentRequest("-s" + stateFilter)); //NOI18N
}
if (dateFilter != null) {
requests.add(1, new ArgumentRequest("-d" + dateFilter)); //NOI18N
}
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.LOG);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
if (!isBuilderSet()) {
builder = null;
}
}
}
/**
* called when server responses with "ok" or "error", (when the command
* finishes)
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* Getter for property defaultBranch, equals the command-line CVS switch
* "-b".
* @return Value of property defaultBranch.
*/
public boolean isDefaultBranch() {
return defaultBranch;
}
/**
* Setter for property defaultBranch, equals the command-line CVS switch
* "-b".
* @param defaultBranch New value of property defaultBranch.
*/
public void setDefaultBranch(boolean defaultBranch) {
this.defaultBranch = defaultBranch;
}
/**
* Getter for property dateFilter, equals the command-line CVS switch "-d".
* @return Value of property dateFilter.
*/
public String getDateFilter() {
return dateFilter;
}
/** Setter for property dateFilter, equals the command-line CVS switch "-d".
* @param dateFilter New value of property dateFilter.
*/
public void setDateFilter(String dateFilter) {
this.dateFilter = dateFilter;
}
/** Getter for property headerOnly, equals the command-line CVS switch "-h".
* @return Value of property headerOnly.
*/
public boolean isHeaderOnly() {
return headerOnly;
}
/** Setter for property headerOnly, equals the command-line CVS switch "-h".
* @param headerOnly New value of property headerOnly.
*/
public void setHeaderOnly(boolean headerOnly) {
this.headerOnly = headerOnly;
}
/** Getter for property noTags, equals the command-line CVS switch "-N".
* @return Value of property noTags.
*/
public boolean isNoTags() {
return noTags;
}
/** Setter for property noTags, equals the command-line CVS switch "-N".
* @param noTags New value of property noTags.
*/
public void setNoTags(boolean noTags) {
this.noTags = noTags;
}
/** Getter for property revisionFilter, equals the command-line CVS switch "-r".
* @return Value of property revisionFilter.
*/
public String getRevisionFilter() {
return revisionFilter;
}
/** Setter for property revisionFilter, equals the command-line CVS switch "-r".
* @param revisionFilter New value of property revisionFilter.
empty string means latest revision of default branch.
*/
public void setRevisionFilter(String revisionFilter) {
this.revisionFilter = revisionFilter;
}
/** Getter for property stateFilter, equals the command-line CVS switch "-s".
* @return Value of property stateFilter.
*/
public String getStateFilter() {
return stateFilter;
}
/** Setter for property stateFilter, equals the command-line CVS switch "-s".
* @param stateFilter New value of property stateFilter.
*/
public void setStateFilter(String stateFilter) {
this.stateFilter = stateFilter;
}
/** Getter for property userFilter, equals the command-line CVS switch "-w".
* @return Value of property userFilter, empty string means the current user.
*/
public String getUserFilter() {
return userFilter;
}
/** Setter for property userFilter, equals the command-line CVS switch "-w".
* @param userFilter New value of property userFilter.
*/
public void setUserFilter(String userFilter) {
this.userFilter = userFilter;
}
/** Getter for property headerAndDescOnly, equals the command-line CVS switch "-t".
* @return Value of property headerAndDescOnly.
*/
public boolean isHeaderAndDescOnly() {
return headerAndDescOnly;
}
/** Setter for property headerAndDescOnly, equals the command-line CVS switch "-t".
* @param headerAndDescOnly New value of property headerAndDescOnly.
*/
public void setHeaderAndDescOnly(boolean headerAndDescOnly) {
this.headerAndDescOnly = headerAndDescOnly;
}
/** This method returns how the command would looklike when typed on the command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("log "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/** takes the arguments and sets the command. To be mainly
* used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'b') {
setDefaultBranch(true);
}
else if (opt == 'h') {
setHeaderOnly(true);
}
else if (opt == 't') {
setHeaderAndDescOnly(true);
}
else if (opt == 'N') {
setNoTags(true);
}
else if (opt == 'd') {
setDateFilter(optArg);
}
else if (opt == 'r') {
setRevisionFilter(optArg == null ? "" : optArg); //NOI18N
// for switches with optional args do that.. ^^^^
}
else if (opt == 's') {
setStateFilter(optArg);
}
else if (opt == 'w') {
setUserFilter(optArg == null ? "" : optArg); //NOI18N
}
else {
return false;
}
return true;
}
public void resetCVSCommand() {
setRecursive(true);
setDefaultBranch(false);
setHeaderOnly(false);
setHeaderAndDescOnly(false);
setNoTags(false);
setDateFilter(null);
setRevisionFilter(null);
setStateFilter(null);
setUserFilter(null);
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "RlbhtNd:r:s:w:"; //NOI18N4
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (isDefaultBranch()) {
toReturn.append("-b "); //NOI18N
}
if (isHeaderAndDescOnly()) {
toReturn.append("-t "); //NOI18N
}
if (isHeaderOnly()) {
toReturn.append("-h "); //NOI18N
}
if (isNoTags()) {
toReturn.append("-N "); //NOI18N
}
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (userFilter != null) {
toReturn.append("-w"); //NOI18N
toReturn.append(userFilter);
toReturn.append(' ');
}
if (revisionFilter != null) {
toReturn.append("-r"); //NOI18N
toReturn.append(revisionFilter);
toReturn.append(' ');
}
if (stateFilter != null) {
toReturn.append("-s"); //NOI18N
toReturn.append(stateFilter);
toReturn.append(' ');
}
if (dateFilter != null) {
toReturn.append("-d"); //NOI18N
toReturn.append(dateFilter);
toReturn.append(' ');
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/log/LogInformation.java 0000644 0001753 0000144 00000036724 11175406777 030063 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.log;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* Describes log information for a file. This is the result of doing a
* cvs log command. The fields in instances of this object are populated
* by response handlers.
* @author Milos Kleint
*/
public class LogInformation extends FileInfoContainer {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); //NOI18N
private File file;
private String repositoryFilename;
private String headRevision;
private String branch;
private String accessList;
private String keywordSubstitution;
private String totalRevisions;
private String selectedRevisions;
private String description;
private String locks;
private final List revisions = new ArrayList();
private final List symbolicNames = new ArrayList();
public LogInformation() {
}
/** Getter for property file.
* @return Value of property file.
*/
public File getFile() {
return file;
}
/** Setter for property file.
* @param file New value of property file.
*/
public void setFile(File file) {
this.file = file;
}
/** Getter for property repositoryFilename.
* @return Value of property repositoryFilename.
*/
public String getRepositoryFilename() {
return repositoryFilename;
}
/** Setter for property repositoryFilename.
* @param repositoryFilename New value of property repositoryFilename.
*/
public void setRepositoryFilename(String repositoryFilename) {
this.repositoryFilename = repositoryFilename;
}
/** Getter for property headRevision.
* @return Value of property headRevision.
*/
public String getHeadRevision() {
return headRevision;
}
/** Setter for property headRevision.
* @param headRevision New value of property headRevision.
*/
public void setHeadRevision(String headRevision) {
this.headRevision = headRevision;
}
/** Getter for property branch.
* @return Value of property branch.
*/
public String getBranch() {
return branch;
}
/** Setter for property branch.
* @param branch New value of property branch.
*/
public void setBranch(String branch) {
this.branch = branch;
}
/** Getter for property accessList.
* @return Value of property accessList.
*/
public String getAccessList() {
return accessList;
}
/** Setter for property accessList.
* @param accessList New value of property accessList.
*/
public void setAccessList(String accessList) {
this.accessList = accessList;
}
/** Getter for property keywordSubstitution.
* @return Value of property keywordSubstitution.
*/
public String getKeywordSubstitution() {
return keywordSubstitution;
}
/** Setter for property keywordSubstitution.
* @param keywordSubstitution New value of property keywordSubstitution.
*/
public void setKeywordSubstitution(String keywordSubstitution) {
this.keywordSubstitution = keywordSubstitution;
}
/** Getter for property totalRevisions.
* @return Value of property totalRevisions.
*/
public String getTotalRevisions() {
return totalRevisions;
}
/** Setter for property totalRevisions.
* @param totalRevisions New value of property totalRevisions.
*/
public void setTotalRevisions(String totalRevisions) {
this.totalRevisions = totalRevisions;
}
/** Getter for property selectedRevisions.
* @return Value of property selectedRevisions.
*/
public String getSelectedRevisions() {
return selectedRevisions;
}
/** Setter for property selectedRevisions.
* @param selectedRevisions New value of property selectedRevisions.
*/
public void setSelectedRevisions(String selectedRevisions) {
this.selectedRevisions = selectedRevisions;
}
/** Getter for property description.
* @return Value of property description.
*/
public String getDescription() {
return description;
}
/** Setter for property description.
* @param description New value of property description.
*/
public void setDescription(String description) {
this.description = description;
}
/** Getter for property locks.
* @return Value of property locks.
*/
public String getLocks() {
return locks;
}
/** Setter for property locks.
* @param locks New value of property locks.
*/
public void setLocks(String locks) {
this.locks = locks;
}
/** adds a revision info to the LogInformation instance
*/
public void addRevision(LogInformation.Revision newRevision) {
revisions.add(newRevision);
}
/** return the all revisions attached to this log
* (if more sophisticated method are supplied, this might get obsolete)
*/
public List getRevisionList() {
return revisions;
}
/** Search the revisions by number of revision. If not found, return null.
*/
public LogInformation.Revision getRevision(String number) {
Iterator it = revisions.iterator();
LogInformation.Revision item;
while (it.hasNext()) {
item = (LogInformation.Revision)it.next();
if (item.getNumber().equals(number)) {
return item;
}
}
return null;
}
/**
* Add a symbolic name to the list of names and attaches it to a revision number.
*/
public void addSymbolicName(String symName, String revisionNumber) {
SymName newName = new SymName();
newName.setName(symName);
newName.setRevision(revisionNumber);
symbolicNames.add(newName);
}
public List getAllSymbolicNames() {
return symbolicNames;
}
/** Search the symbolic names by number of revision. If not found, return null.
*/
public List getSymNamesForRevision(String revNumber) {
Iterator it = symbolicNames.iterator();
LogInformation.SymName item;
List list = new LinkedList();
while (it.hasNext()) {
item = (LogInformation.SymName)it.next();
if (item.getRevision().equals(revNumber)) {
list.add(item);
}
}
return list;
}
/** Search the symbolic names by name of tag (symbolic name). If not found, return null.
*/
public LogInformation.SymName getSymName(String symName) {
Iterator it = symbolicNames.iterator();
LogInformation.SymName item;
while (it.hasNext()) {
item = (LogInformation.SymName)it.next();
if (item.getName().equals(symName)) {
return item;
}
}
return null;
}
public Revision createNewRevision(String number) {
Revision rev = new Revision();
rev.setNumber(number);
return rev;
}
/**
* Return a string representation of this object. Useful for debugging.
*/
public String toString() {
StringBuffer buf = new StringBuffer(30);
buf.append("\nFile: " + ((file != null)?file.getAbsolutePath():"null")); //NOI18N
buf.append("\nRepositoryFile: " + repositoryFilename); //NOI18N
buf.append("\nHead revision: " + headRevision); //NOI18N
return buf.toString();
}
public class SymName {
private String name;
private String revision;
public SymName() {
}
public String getName() {
return name;
}
public void setName(String symName) {
name = symName;
}
public void setRevision(String rev) {
revision = rev;
}
public String getRevision() {
return revision;
}
/**
* Determines if given name represents a branch tag
* test is based on revision num parsing and looking
* for trailing 0.# (1.1.0.2, 1.2.4.5.0.6, ,..).
*/
public final boolean isBranch() {
boolean branch = false;
String[] nums = revision.split("\\.");
if (nums.length > 2 && (nums.length % 2) == 0) {
String lastButOne = nums[nums.length -2];
branch = "0".equals(lastButOne); // NOI18N
}
return branch;
}
}
public class Revision {
/**
* The revision number.
*/
private String number;
/**
* The parsed date.
*/
private Date date;
/**
* The String representation of the date.
*/
private String dateString;
/**
* The author of the revision.
*/
private String author;
/**
* The state.
*/
private String state;
/**
* The added/removed lines.
*/
private String lines;
/**
* The commit ID, as generated and reported by some servers.
*/
private String commitID;
/**
* The commit log-message.
*/
private String message;
/**
* The branches for this revision.
*/
private String branches;
public Revision() {
/**
* Since these have to be initialized when correctly parsing the
* command's output, then initializing them to empty strings
* is a safety measure against bad parsing errors.
* what about backward compatibility here??
*
state = "";
lines = "";
message = "";
branches = "";
*/
}
public LogInformation getLogInfoHeader() {
return LogInformation.this;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Date getDate() {
return date;
}
public String getDateString() {
return dateString;
}
/**
* @deprecated This method uses a static parser to parse dates which is not thread safe, use #setDate instead
*/
public void setDateString(String dateString) {
this.dateString = dateString;
if (dateString == null) {
this.date = null;
return;
}
// Parse the date ...
try {
// some servers use dashes to separate date components, so replace with slashes
// also add a default GMT timezone at the end, if the server already put one in this one will be ignored by the parser
dateString = dateString.replace('/', '-') + " +0000";
this.date = DATE_FORMAT.parse(dateString);
}
catch (Exception ex) {
BugLog.getInstance().bug("Couldn't parse date " + dateString);
}
}
public void setDate(Date date, String dateString) {
this.dateString = dateString;
this.date = date;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getLines() {
return lines;
}
public void setLines(String lines) {
this.lines = lines;
}
public String getCommitID() {
return commitID;
}
public void setCommitID(String commitID) {
this.commitID = commitID;
}
/**
* Returns how many lines were added in this revision.
*/
public int getAddedLines() {
if (lines != null) {
int start = lines.indexOf('+');
int end = lines.indexOf(' ');
if (start >= 0 && end > start) {
String added = lines.substring(start + 1, end);
try {
int toReturn = Integer.parseInt(added);
return toReturn;
} catch (NumberFormatException exc) {
//TODO BUGLog..
}
}
}
return 0;
}
public int getRemovedLines() {
if (lines != null) {
int start = lines.indexOf('-');
if (start >= 0) {
String removed = lines.substring(start + 1);
try {
int toReturn = Integer.parseInt(removed);
return toReturn;
} catch (NumberFormatException exc) {
//TODO BUGLog..
}
}
}
return 0;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getBranches() {
return branches;
}
public void setBranches(String branches) {
this.branches = branches;
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/log/RlogCommand.java 0000644 0001753 0000144 00000035354 11175406777 027334 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.log;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The rlog command is similar to log, but doens't operate on currently checked
* out sources.
*
* @author MIlos Kleint
*/
public class RlogCommand extends BasicCommand {
/**
* The modules to rlog.
*/
private final List modules = new LinkedList();
/**
* Holds value of property defaultBranch.
*/
private boolean defaultBranch;
/**
* Holds value of property dateFilter.
*/
private String dateFilter;
/**
* Holds value of property headerOnly.
*/
private boolean headerOnly;
/**
* Holds value of property suppressHeader.
*/
private boolean suppressHeader;
/**
* Holds value of property noTags.
*/
private boolean noTags;
/**
* Holds value of property revisionFilter.
*/
private String revisionFilter;
/**
* Holds value of property stateFilter.
*/
private String stateFilter;
/**
* Holds value of property userFilter.
*/
private String userFilter;
/**
* Holds value of property headerAndDescOnly.
*/
private boolean headerAndDescOnly;
public RlogCommand() {
resetCVSCommand();
}
/**
* Set the modules to export.
* @param theModules the names of the modules to export
*/
public void setModule(String module) {
modules.add(module);
}
/**
* clears the list of modules for export.
*/
public void clearModules() {
this.modules.clear();
}
/**
* Set the modules to export.
* @param theModules the names of the modules to export
*/
public void setModules(String[] modules) {
clearModules();
if (modules == null) {
return;
}
for (int i = 0; i < modules.length; i++) {
String module = modules[i];
this.modules.add(module);
}
}
public String[] getModules() {
String[] mods = new String[modules.size()];
mods = (String[])modules.toArray(mods);
return mods;
}
/**
* Getter for property defaultBranch, equals the command-line CVS switch
* "-b".
* @return Value of property defaultBranch.
*/
public boolean isDefaultBranch() {
return defaultBranch;
}
/**
* Setter for property defaultBranch, equals the command-line CVS switch
* "-b".
* @param defaultBranch New value of property defaultBranch.
*/
public void setDefaultBranch(boolean defaultBranch) {
this.defaultBranch = defaultBranch;
}
/**
* Getter for property dateFilter, equals the command-line CVS switch "-d".
* @return Value of property dateFilter.
*/
public String getDateFilter() {
return dateFilter;
}
/** Setter for property dateFilter, equals the command-line CVS switch "-d".
* @param dateFilter New value of property dateFilter.
*/
public void setDateFilter(String dateFilter) {
this.dateFilter = dateFilter;
}
/** Getter for property headerOnly, equals the command-line CVS switch "-h".
* @return Value of property headerOnly.
*/
public boolean isHeaderOnly() {
return headerOnly;
}
/** Setter for property headerOnly, equals the command-line CVS switch "-h".
* @param headerOnly New value of property headerOnly.
*/
public void setHeaderOnly(boolean headerOnly) {
this.headerOnly = headerOnly;
}
/** Getter for property suppressHeader, equals the command-line CVS switch "-S".
* @return Value of property suppressHeader.
*/
public boolean isSuppressHeader() {
return suppressHeader;
}
/** Setter for property headerOnly, equals the command-line CVS switch "-S".
* @param suppressHeader New value of property suppressHeader.
*/
public void setSuppressHeader(boolean suppressHeader) {
this.suppressHeader = suppressHeader;
}
/** Getter for property noTags, equals the command-line CVS switch "-N".
* @return Value of property noTags.
*/
public boolean isNoTags() {
return noTags;
}
/** Setter for property noTags, equals the command-line CVS switch "-N".
* @param noTags New value of property noTags.
*/
public void setNoTags(boolean noTags) {
this.noTags = noTags;
}
/** Getter for property revisionFilter, equals the command-line CVS switch "-r".
* @return Value of property revisionFilter.
*/
public String getRevisionFilter() {
return revisionFilter;
}
/** Setter for property revisionFilter, equals the command-line CVS switch "-r".
* @param revisionFilter New value of property revisionFilter.
empty string means latest revision of default branch.
*/
public void setRevisionFilter(String revisionFilter) {
this.revisionFilter = revisionFilter;
}
/** Getter for property stateFilter, equals the command-line CVS switch "-s".
* @return Value of property stateFilter.
*/
public String getStateFilter() {
return stateFilter;
}
/** Setter for property stateFilter, equals the command-line CVS switch "-s".
* @param stateFilter New value of property stateFilter.
*/
public void setStateFilter(String stateFilter) {
this.stateFilter = stateFilter;
}
/** Getter for property userFilter, equals the command-line CVS switch "-w".
* @return Value of property userFilter, empty string means the current user.
*/
public String getUserFilter() {
return userFilter;
}
/** Setter for property userFilter, equals the command-line CVS switch "-w".
* @param userFilter New value of property userFilter.
*/
public void setUserFilter(String userFilter) {
this.userFilter = userFilter;
}
/** Getter for property headerAndDescOnly, equals the command-line CVS switch "-t".
* @return Value of property headerAndDescOnly.
*/
public boolean isHeaderAndDescOnly() {
return headerAndDescOnly;
}
/** Setter for property headerAndDescOnly, equals the command-line CVS switch "-t".
* @param headerAndDescOnly New value of property headerAndDescOnly.
*/
public void setHeaderAndDescOnly(boolean headerAndDescOnly) {
this.headerAndDescOnly = headerAndDescOnly;
}
/**
* Execute this command.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
super.execute(client, em);
//
// moved modules code to the end of the other arguments --GAR
//
if (!isRecursive())
{
requests.add(new ArgumentRequest("-l")); //NOI18N
}
// first send out all possible parameters..
if (defaultBranch) {
requests.add(new ArgumentRequest("-b")); //NOI18N
}
if (headerAndDescOnly) {
requests.add(new ArgumentRequest("-t")); //NOI18N
}
if (headerOnly) {
requests.add(new ArgumentRequest("-h")); //NOI18N
}
if (suppressHeader) {
requests.add(new ArgumentRequest("-S")); //NOI18IN
}
if (noTags) {
requests.add(new ArgumentRequest("-N")); //NOI18N
}
if (userFilter != null) {
requests.add(new ArgumentRequest("-w" + userFilter)); //NOI18N
}
if (revisionFilter != null) {
requests.add(new ArgumentRequest("-r" + revisionFilter)); //NOI18N
}
if (stateFilter != null) {
requests.add(new ArgumentRequest("-s" + stateFilter)); //NOI18N
}
if (dateFilter != null) {
requests.add(new ArgumentRequest("-d" + dateFilter)); //NOI18N
}
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
requests.add(new ArgumentRequest(module));
}
requests.add(CommandRequest.RLOG);
try {
client.processRequests(requests);
requests.clear();
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
}
/**
* Don't send status of local files prior to executing command, as it's not
* needed.
*/
protected boolean assumeLocalPathWhenUnspecified() {
return false;
}
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("rlog "); //NOI18N
toReturn.append(getCVSArguments());
if (modules != null && modules.size() > 0) {
for (Iterator it = modules.iterator(); it.hasNext();) {
String module = (String)it.next();
toReturn.append(module);
toReturn.append(' ');
}
}
else {
String localizedMsg = CommandException.getLocalMessage("ExportCommand.moduleEmpty.text"); //NOI18N
toReturn.append(" "); //NOI18N
toReturn.append(localizedMsg);
}
return toReturn.toString();
}
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (isDefaultBranch()) {
toReturn.append("-b "); //NOI18N
}
if (isHeaderAndDescOnly()) {
toReturn.append("-t "); //NOI18N
}
if (isHeaderOnly()) {
toReturn.append("-h "); //NOI18N
}
if (isSuppressHeader()) {
toReturn.append("-S "); //NOI18N
}
if (isNoTags()) {
toReturn.append("-N "); //NOI18N
}
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (userFilter != null) {
toReturn.append("-w"); //NOI18N
toReturn.append(userFilter);
toReturn.append(' ');
}
if (revisionFilter != null) {
toReturn.append("-r"); //NOI18N
toReturn.append(revisionFilter);
toReturn.append(' ');
}
if (stateFilter != null) {
toReturn.append("-s"); //NOI18N
toReturn.append(stateFilter);
toReturn.append(' ');
}
if (dateFilter != null) {
toReturn.append("-d"); //NOI18N
toReturn.append(dateFilter);
toReturn.append(' ');
}
return toReturn.toString();
}
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'b') {
setDefaultBranch(true);
}
else if (opt == 'h') {
setHeaderOnly(true);
}
else if (opt == 't') {
setHeaderAndDescOnly(true);
}
else if (opt == 'S') {
setSuppressHeader(true);
}
else if (opt == 'N') {
setNoTags(true);
}
else if (opt == 'd') {
setDateFilter(optArg);
}
else if (opt == 'r') {
setRevisionFilter(optArg == null ? "" : optArg); //NOI18N
// for switches with optional args do that.. ^^^^
}
else if (opt == 's') {
setStateFilter(optArg);
}
else if (opt == 'w') {
setUserFilter(optArg == null ? "" : optArg); //NOI18N
}
else {
return false;
}
return true;
}
public void resetCVSCommand() {
setRecursive(true);
setDefaultBranch(false);
setHeaderOnly(false);
setHeaderAndDescOnly(false);
setSuppressHeader(false);
setNoTags(false);
setDateFilter(null);
setRevisionFilter(null);
setStateFilter(null);
setUserFilter(null);
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "RlbhStNd:r:s:w:"; //NOI18N4
}
/**
* Create a builder for this command.
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventMan) {
return new LogBuilder(eventMan, this);
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/remove/ 0000755 0001753 0000144 00000000000 11175434236 024760 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/remove/RemoveBuilder.java 0000644 0001753 0000144 00000013436 11175407000 030363 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.remove;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of remove information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
*/
public class RemoveBuilder implements Builder {
private static final String UNKNOWN = ": nothing known about"; //NOI18N
private static final String WARNING = ": warning: "; //NOI18N
private static final String SCHEDULING = ": scheduling `"; //NOI18N
private static final String USE_COMMIT = ": use 'cvs commit' "; //NOI18N
private static final String DIRECTORY = ": Removing "; //NOI18N
private static final String STILL_IN_WORKING = ": file `"; //NOI18N
private static final String REMOVE_FIRST = "first"; //NOI18N
private static final String UNKNOWN_FILE = "?"; //NOI18N
/**
* The status object that is currently being built
*/
private RemoveInformation removeInformation;
/**
* The directory in which the file being processed lives. This is
* relative to the local directory
*/
private String fileDirectory;
/**
* The event manager to use
*/
private final EventManager eventManager;
private final RemoveCommand removeCommand;
public RemoveBuilder(EventManager eventManager, RemoveCommand removeCommand) {
this.eventManager = eventManager;
this.removeCommand = removeCommand;
}
public void outputDone() {
if (removeInformation != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, removeInformation));
removeInformation = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (line.indexOf(SCHEDULING) >= 0) {
int endingIndex = line.indexOf('\'');
String fn = line.substring(line.indexOf(SCHEDULING) + SCHEDULING.length(), endingIndex).trim();
addFile(fn);
removeInformation.setRemoved(true);
outputDone();
}
if (line.startsWith(UNKNOWN_FILE)) {
addFile(line.substring(UNKNOWN_FILE.length()));
removeInformation.setRemoved(false);
outputDone();
}
if (line.indexOf(STILL_IN_WORKING) >= 0) {
int endingIndex = line.indexOf('\'');
String fn = line.substring(line.indexOf(STILL_IN_WORKING) + STILL_IN_WORKING.length(), endingIndex).trim();
addFile(fn);
removeInformation.setRemoved(false);
outputDone();
}
// ignore the rest..
}
protected File createFile(String fileName) {
StringBuffer path = new StringBuffer();
path.append(removeCommand.getLocalDirectory());
path.append(File.separator);
if (fileDirectory == null) {
// happens for single files only
// (for directories, the dir name is always sent before the actual files)
File locFile = removeCommand.getFileEndingWith(fileName);
if (locFile == null) {
path.append(fileName);
}
else {
path = new StringBuffer(locFile.getAbsolutePath());
}
}
else {
// path.append(fileDirectory);
// path.append(File.separator);
path.append(fileName);
}
String toReturn = path.toString();
toReturn = toReturn.replace('/', File.separatorChar);
return new File(path.toString());
}
protected void addFile(String name) {
removeInformation = new RemoveInformation();
removeInformation.setFile(createFile(name));
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/remove/RemoveCommand.java 0000644 0001753 0000144 00000023246 11175407000 030353 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.remove;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* The remove command is used to remove files and directories from the
* repository.
* @author Robert Greig
*/
public class RemoveCommand extends BasicCommand {
/**
* If true, will delete the file in working dir before it gets removed.
*/
private boolean deleteBeforeRemove;
private boolean ignoreLocallyExistingFiles;
/**
* Returns true if the local files will be deleted automatically.
*/
public boolean isDeleteBeforeRemove() {
return deleteBeforeRemove;
}
/**
* Sets whether the local files will be deleted before.
*/
public void setDeleteBeforeRemove(boolean deleteBeforeRemove) {
this.deleteBeforeRemove = deleteBeforeRemove;
}
/**
* Returns true to indicate that locally existing files are treated as they
* would not exist.
* This is a extension to the standard cvs-behaviour!
* @deprecated
*/
public boolean doesIgnoreLocallyExistingFiles() {
return ignoreLocallyExistingFiles;
}
/**
* Returns true to indicate that locally existing files are treated as they
* would not exist.
* This is a extension to the standard cvs-behaviour!
*/
public boolean isIgnoreLocallyExistingFiles() {
return ignoreLocallyExistingFiles;
}
/**
* Sets whether locally existing files will be treated as they were deleted
* before.
* This is a extension to the standard cvs-behaviour!
*/
public void setIgnoreLocallyExistingFiles(boolean ignoreLocallyExistingFiles) {
this.ignoreLocallyExistingFiles = ignoreLocallyExistingFiles;
}
/**
* Method that is called while the command is being executed.
* Descendants can override this method to return a Builder instance
* that will parse the server's output and create data structures.
*/
public Builder createBuilder(EventManager eventMan) {
return new RemoveBuilder(eventMan, this);
}
/**
* Executes this command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
if (files == null || files.length == 0) {
throw new CommandException("No files have been specified for " + //NOI18N
"removal.", CommandException.getLocalMessage("RemoveCommand.noFilesSpecified", null)); //NOI18N
}
client.ensureConnection();
if (isDeleteBeforeRemove()) {
removeAll(files);
}
super.execute(client, em);
try {
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.REMOVE);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
protected void sendEntryAndModifiedRequests(Entry entry, File file) {
super.sendEntryAndModifiedRequests(entry,
isIgnoreLocallyExistingFiles() ? null : file);
if (entry.getRevision().equals("0")) {
// zero means a locally added file, not yet commited.
try {
clientServices.removeEntry(file);
} catch (IOException exc) {
BugLog.getInstance().showException(exc);
}
}
}
/**
* This method returns how the command would looks like when typed on the
* command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("remove "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName() + " "); //NOI18N
}
}
return toReturn.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file).
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'f') {
setDeleteBeforeRemove(true);
}
else {
return false;
}
return true;
}
/**
* Deletes all files being removed from the working directory.
* Doesn't delete directories.
* Attempts a recursive delete
* @throws CommandException - in case the file cannot be deleted.
*/
private void removeAll(File[] filesToDel)
throws CommandException {
if (filesToDel == null) {
return;
}
for (int index = 0; index < filesToDel.length; index++) {
File file = filesToDel[index];
if (file.exists() && file.isFile()) {
if (!file.delete()) {
throw new CommandException("Cannot delete file " + file.getAbsolutePath(), //NOI18N
CommandException.getLocalMessage("RemoveCommand.cannotDelete", new Object[]{file.getAbsolutePath()})); //NOI18N
}
}
else {
// For directories remove only it's files.
// Preserve the cvs structure though.
if (isRecursive() &&
!file.getName().equalsIgnoreCase("CVS")) { //NOI18N
removeAll(file.listFiles());
}
}
}
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "flR"; //NOI18N
}
/**
* resets all switches in the command. After calling this method,
* the command should have no switches defined and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setDeleteBeforeRemove(false);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (isDeleteBeforeRemove()) {
toReturn.append("-f "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/remove/RemoveInformation.java 0000644 0001753 0000144 00000006230 11175407000 031254 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.remove;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
/**
* Describes remove information for a file. This is the result of doing a
* cvs remove command. The fields in instances of this object are populated
* by response handlers.
*
* @author Milos Kleint
*/
public class RemoveInformation extends FileInfoContainer {
private File file;
private boolean removed;
public RemoveInformation() {
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void setRemoved(boolean rem) {
removed = rem;
}
public boolean isRemoved() {
return removed;
}
/**
* Return a string representation of this object. Useful for debugging.
*/
public String toString() {
StringBuffer buf = new StringBuffer(30);
buf.append(" "); //NOI18N
buf.append((file != null)
? file.getAbsolutePath()
:"null"); //NOI18N
return buf.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/status/ 0000755 0001753 0000144 00000000000 11175434236 025006 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/status/StatusBuilder.java 0000644 0001753 0000144 00000025114 11175407000 030433 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.status;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.file.*;
/**
* Handles the building of a status information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
* @author Thomas Singer
*/
public class StatusBuilder implements Builder {
private static final String UNKNOWN = ": nothing known about"; //NOI18N
private static final String EXAM_DIR = ": Examining"; //NOI18N
private static final String NOT_IN_REPOSITORY = "No revision control file"; //NOI18N
private static final String FILE = "File: "; //NOI18N
private static final String STATUS = "Status:"; //NOI18N
private static final String NO_FILE_FILENAME = "no file"; //NOI18N
private static final String WORK_REV = " Working revision:"; //NOI18N
private static final String REP_REV = " Repository revision:"; //NOI18N
private static final String TAG = " Sticky Tag:"; //NOI18N
private static final String DATE = " Sticky Date:"; //NOI18N
private static final String OPTIONS = " Sticky Options:"; //NOI18N
private static final String EXISTING_TAGS = " Existing Tags:"; //NOI18N
private static final String EMPTY_BEFORE_TAGS = " "; //NOI18N
private static final String NO_TAGS = " No Tags Exist"; //NOI18N
private static final String UNKNOWN_FILE = "? "; //NOI18N
/**
* The status object that is currently being built.
*/
private StatusInformation statusInformation;
/**
* The event manager to use.
*/
private EventManager eventManager;
private final StatusCommand statusCommand;
private String relativeDirectory;
private final String localPath;
private boolean beginning;
private boolean readingTags;
private final File[] fileArray;
/**
* Creates a StatusBuilder.
*/
public StatusBuilder(EventManager eventManager,
StatusCommand statusCommand) {
this.eventManager = eventManager;
this.statusCommand = statusCommand;
File[] fileArray = statusCommand.getFiles();
if (fileArray != null) {
this.fileArray = new File[fileArray.length];
System.arraycopy(fileArray, 0, this.fileArray, 0, fileArray.length);
}
else {
this.fileArray = null;
}
this.localPath = statusCommand.getLocalDirectory();
this.beginning = true;
}
public void outputDone() {
if (statusInformation != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, statusInformation));
statusInformation = null;
readingTags = false;
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (readingTags) {
if (line.startsWith(NO_TAGS)) {
outputDone();
return;
}
int bracket = line.indexOf("\t(");
if (bracket > 0) {
// it's another tag..
String tag = line.substring(0, bracket).trim();
String rev = line.substring(bracket + 2, line.length() - 1);
if (statusInformation == null) {
statusInformation = new StatusInformation();
}
statusInformation.addExistingTag(tag, rev);
}
else {
outputDone();
return;
}
}
if (line.startsWith(UNKNOWN_FILE) && beginning) {
File file = new File(localPath, line.substring(UNKNOWN_FILE.length()));
statusInformation = new StatusInformation();
statusInformation.setFile(file);
statusInformation.setStatusString(FileStatus.UNKNOWN.toString());
outputDone();
}
if (line.startsWith(UNKNOWN)) {
outputDone();
beginning = false;
}
else if (line.indexOf(EXAM_DIR) >= 0) {
relativeDirectory = line.substring(line.indexOf(EXAM_DIR) + EXAM_DIR.length()).trim();
beginning = false;
}
else if (line.startsWith(FILE)) {
outputDone();
statusInformation = new StatusInformation();
processFileAndStatusLine(line.substring(FILE.length()));
beginning = false;
}
else if (line.startsWith(WORK_REV)) {
processWorkRev(line.substring(WORK_REV.length()));
}
else if (line.startsWith(REP_REV)) {
processRepRev(line.substring(REP_REV.length()));
/* if (statusInformation.getRepositoryRevision().startsWith(NOT_IN_REPOSITORY))
{
outputDone();
}
*/
}
else if (line.startsWith(TAG)) {
processTag(line.substring(TAG.length()));
}
else if (line.startsWith(DATE)) {
processDate(line.substring(DATE.length()));
}
else if (line.startsWith(OPTIONS)) {
processOptions(line.substring(OPTIONS.length()));
if (!statusCommand.isIncludeTags()) {
outputDone();
}
}
else if (line.startsWith(EXISTING_TAGS)) {
readingTags = true;
}
}
private File createFile(String fileName) {
File file = null;
if (relativeDirectory != null) {
if (relativeDirectory.trim().equals(".")) { //NOI18N
file = new File(localPath, fileName);
}
else {
file = new File(localPath, relativeDirectory + '/' + fileName);
}
}
else if (fileArray != null) {
for (int i = 0; i < fileArray.length; i++) {
File currentFile = fileArray[i];
if (currentFile == null || currentFile.isDirectory()) {
continue;
}
String currentFileName = currentFile.getName();
if (fileName.equals(currentFileName)) {
fileArray[i] = null;
file = currentFile;
break;
}
}
}
if (file == null) {
System.err.println("JAVACVS ERROR!! wrong algorithm for assigning path to single files(1)!!");
}
return file;
}
private void processFileAndStatusLine(String line) {
int statusIndex = line.lastIndexOf(STATUS);
String fileName = line.substring(0, statusIndex).trim();
if (fileName.startsWith(NO_FILE_FILENAME)) {
fileName = fileName.substring(8);
}
statusInformation.setFile(createFile(fileName));
String status = new String(line.substring(statusIndex + 8).trim());
statusInformation.setStatusString(status);
}
private boolean assertNotNull() {
if (statusInformation == null) {
System.err.println("Bug: statusInformation must not be null!");
return false;
}
return true;
}
private void processWorkRev(String line) {
if (!assertNotNull()) {
return;
}
statusInformation.setWorkingRevision(line.trim().intern());
}
private void processRepRev(String line) {
if (!assertNotNull()) {
return;
}
line = line.trim();
if (line.startsWith(NOT_IN_REPOSITORY)) {
statusInformation.setRepositoryRevision(line.trim().intern());
return;
}
int firstSpace = line.indexOf('\t');
if (firstSpace > 0) {
statusInformation.setRepositoryRevision(
line.substring(0, firstSpace).trim().intern());
statusInformation.setRepositoryFileName(
new String(line.substring(firstSpace).trim()));
}
else {
statusInformation.setRepositoryRevision(""); //NOI18N
statusInformation.setRepositoryFileName(""); //NOI18N
}
}
private void processTag(String line) {
if (!assertNotNull()) {
return;
}
statusInformation.setStickyTag(line.trim().intern());
}
private void processDate(String line) {
if (!assertNotNull()) {
return;
}
statusInformation.setStickyDate(line.trim().intern());
}
private void processOptions(String line) {
if (!assertNotNull()) {
return;
}
statusInformation.setStickyOptions(line.trim().intern());
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/status/StatusCommand.java 0000644 0001753 0000144 00000015753 11175407000 030433 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.status;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The status command looks up the status of files in the repository
* @author Robert Greig
*/
public class StatusCommand extends BasicCommand {
/**
* The event manager to use
*/
private EventManager eventManager;
/**
* Holds value of property includeTags.
*/
private boolean includeTags;
/**
* Construct a new status command
*/
public StatusCommand() {
}
/**
* Create a builder for this command.
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventManager) {
return new StatusBuilder(eventManager, this);
}
/**
* Execute a command
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually process
* all the requests.
*/
public void execute(ClientServices client, EventManager em)
throws CommandException, AuthenticationException {
client.ensureConnection();
eventManager = em;
super.execute(client, em);
try {
// parameters come now..
if (includeTags) {
requests.add(1, new ArgumentRequest("-v")); //NOI18N
}
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.STATUS);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception e) {
throw new CommandException(e, e.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* Getter for property includeTags.
* @return Value of property includeTags.
*/
public boolean isIncludeTags() {
return includeTags;
}
/**
* Setter for property includeTags.
* @param includeTags New value of property includeTags.
*/
public void setIncludeTags(boolean inclTags) {
includeTags = inclTags;
}
/**
* called when server responses with "ok" or "error", (when the command finishes)
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* This method returns how the command would looklike when typed on the command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("status "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* takes the arguments and sets the command. To be mainly
* used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'v') {
setIncludeTags(true);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "Rlv"; //NOI18N
}
/**
* resets all switches in the command. After calling this method,
* the command should have no switches defined and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setIncludeTags(false);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (isIncludeTags()) {
toReturn.append("-v "); //NOI18N
}
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/status/StatusInformation.java 0000644 0001753 0000144 00000026172 11175407000 031337 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.status;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.file.*;
/**
* Describes status information for a file. This is the result of doing a
* cvs status command. The fields in instances of this object are populated
* by response handlers.
* @author Robert Greig
*/
public class StatusInformation extends FileInfoContainer {
// Fields =================================================================
private File file;
private FileStatus status;
private String workingRevision;
private String repositoryRevision;
private String repositoryFileName;
private String stickyDate;
private String stickyOptions;
private String stickyTag;
/**
* Hold key pairs of existing tags.
*/
private List tags;
private StringBuffer symNamesBuffer;
public StatusInformation() {
setAllExistingTags(null);
}
/**
* Getter for property file.
* @return Value of property file.
*/
public File getFile() {
return file;
}
/**
* Setter for property file.
* @param file New value of property file.
*/
public void setFile(File file) {
this.file = file;
}
/**
* Getter for property status.
* @return Value of property status.
*/
public FileStatus getStatus() {
return status;
}
/**
* Setter for property status.
* @param status New value of property status.
*/
public void setStatus(FileStatus status) {
this.status = status;
}
/**
* Returns the status as a String.
* The String returned are definitely the static-final-instances.
*/
public String getStatusString() {
if (status == null) {
return null;
}
return status.toString();
}
/**
* Sets the status by the specified string.
*/
public void setStatusString(String statusString) {
setStatus(FileStatus.getStatusForString(statusString));
}
/**
* Getter for property workingRevision.
* @return Value of property workingRevision.
*/
public String getWorkingRevision() {
return workingRevision;
}
/**
* Setter for property workingRevision.
* @param workingRevision New value of property workingRevision.
*/
public void setWorkingRevision(String workingRevision) {
this.workingRevision = workingRevision;
}
/**
* Getter for property repositoryRevision.
* @return Value of property repositoryRevision.
*/
public String getRepositoryRevision() {
return repositoryRevision;
}
/**
* Setter for property repositoryRevision.
* @param repositoryRevision New value of property repositoryRevision.
*/
public void setRepositoryRevision(String repositoryRevision) {
this.repositoryRevision = repositoryRevision;
}
/**
* Getter for property repositoryFileName.
* @return Value of property repositoryFileName.
*/
public String getRepositoryFileName() {
return repositoryFileName;
}
/**
* Setter for property repositoryFileName.
* @param repositoryRevision New value of property repositoryFileName.
*/
public void setRepositoryFileName(String repositoryFileName) {
this.repositoryFileName = repositoryFileName;
}
/**
* Getter for property stickyTag.
* @return Value of property stickyTag.
*/
public String getStickyTag() {
return stickyTag;
}
/**
* Setter for property stickyTag.
* @param stickyTag New value of property stickyTag.
*/
public void setStickyTag(String stickyTag) {
this.stickyTag = stickyTag;
}
/**
* Getter for property stickyDate.
* @return Value of property stickyDate.
*/
public String getStickyDate() {
return stickyDate;
}
/**
* Setter for property stickyDate.
* @param stickyDate New value of property stickyDate.
*/
public void setStickyDate(String stickyDate) {
this.stickyDate = stickyDate;
}
/**
* Getter for property stickyOptions.
* @return Value of property stickyOptions.
*/
public String getStickyOptions() {
return stickyOptions;
}
/**
* Setter for property stickyOptions.
* @param stickyOptions New value of property stickyOptions.
*/
public void setStickyOptions(String stickyOptions) {
this.stickyOptions = stickyOptions;
}
public void addExistingTag(String tagName, String revisionNumber) {
if (symNamesBuffer == null) {
symNamesBuffer = new StringBuffer();
}
symNamesBuffer.append(tagName);
symNamesBuffer.append(" "); //NOI18N
symNamesBuffer.append(revisionNumber);
symNamesBuffer.append("\n"); //NOI18N
}
private void createSymNames() {
tags = new LinkedList();
if (symNamesBuffer == null) {
return;
}
int length = 0;
int lastLength = 0;
while (length < symNamesBuffer.length()) {
while (length < symNamesBuffer.length() && symNamesBuffer.charAt(length) != '\n') {
length++;
}
if (length > lastLength) {
String line = symNamesBuffer.substring(lastLength, length);
String symName = line.substring(0, line.indexOf(' '));
String revisionNumber = line.substring(line.indexOf(' ') + 1);
SymName newName = new SymName();
newName.setTag(symName);
newName.setRevision(revisionNumber);
tags.add(newName);
lastLength = length + 1;
length++;
}
}
symNamesBuffer = null;
}
public List getAllExistingTags() {
if (tags == null) {
createSymNames();
}
return tags;
}
public void setAllExistingTags(List tags) {
this.tags = tags;
}
/** Search the symbolic names by number of revision. If not found, return null.
*/
public List getSymNamesForRevision(String revNumber) {
if (tags == null) {
createSymNames();
}
List list = new LinkedList();
for (Iterator it = tags.iterator(); it.hasNext();) {
StatusInformation.SymName item = (StatusInformation.SymName)it.next();
if (item.getRevision().equals(revNumber)) {
list.add(item);
}
}
return list;
}
/**
* Search the symbolic names by name of tag (symbolic name).
* If not found, return null.
*/
public StatusInformation.SymName getSymNameForTag(String tagName) {
if (tags == null) {
createSymNames();
}
for (Iterator it = tags.iterator(); it.hasNext();) {
StatusInformation.SymName item = (StatusInformation.SymName)it.next();
if (item.getTag().equals(tagName)) {
return item;
}
}
return null;
}
/**
* Return a string representation of this object. Useful for debugging.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("\nFile: "); //NOI18N
buf.append((file != null) ? file.getAbsolutePath()
: "null"); //NOI18N
buf.append("\nStatus is: "); //NOI18N
buf.append(getStatusString());
buf.append("\nWorking revision: "); //NOI18N
buf.append(workingRevision);
buf.append("\nRepository revision: "); //NOI18N
buf.append("\nSticky date: "); //NOI18N
buf.append(stickyDate);
buf.append("\nSticky options: "); //NOI18N
buf.append(stickyOptions);
buf.append("\nSticky tag: "); //NOI18N
buf.append(stickyTag);
if (tags != null && tags.size() > 0) {
// we are having some tags to print
buf.append("\nExisting Tags:"); //NOI18N
for (Iterator it = tags.iterator(); it.hasNext();) {
buf.append("\n "); //NOI18N
buf.append(it.next().toString());
}
}
return buf.toString();
}
/**
* An inner class storing information about a symbolic name.
* Consists of a pair of Strings. tag + revision.
*/
public static class SymName {
private String tag;
private String revision;
public SymName() {
}
public String getTag() {
return tag;
}
public void setTag(String symName) {
tag = symName;
}
public void setRevision(String rev) {
revision = rev;
}
public String getRevision() {
return revision;
}
public String toString() {
return getTag() + " : " + getRevision(); //NOI18N
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/tag/ 0000755 0001753 0000144 00000000000 11175434236 024236 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/tag/RtagCommand.java 0000644 0001753 0000144 00000030525 11175407000 027267 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.tag;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The rtag command adds or deletes a tag to the specified files/directories in
* the repository.
*
* @author Martin Entlicher
*/
public class RtagCommand extends RepositoryCommand {
/**
* The event manager to use.
*/
private EventManager eventManager;
private boolean clearFromRemoved;
private boolean deleteTag;
private boolean makeBranchTag;
private boolean overrideExistingTag;
private boolean matchHeadIfRevisionNotFound;
private boolean noExecTagProgram;
private String tag;
private String tagByDate;
private String tagByRevision;
/**
* Construct a new tag command.
*/
public RtagCommand() {
}
/**
* Creates the TagBuilder.
* @param eventManager the event manager used to received cvs events
*/
public Builder createBuilder(EventManager eventManager) {
return new TagBuilder(eventManager, getLocalDirectory());
}
/**
* Returns true if the tag from removed files is cleared.
*/
public boolean isClearFromRemoved() {
return clearFromRemoved;
}
/**
* Clear tag from removed files
*/
public void setClearFromRemoved(boolean clearFromRemoved) {
this.clearFromRemoved = clearFromRemoved;
}
/**
* Returns true if the tag should be deleted (otherwise added).
*/
public boolean isDeleteTag() {
return deleteTag;
}
/**
* Sets whether the tag should be deleted (true) or added (false).
*/
public void setDeleteTag(boolean deleteTag) {
this.deleteTag = deleteTag;
}
/**
* Returns true if the tag should be a branch tag.
*/
public boolean isMakeBranchTag() {
return makeBranchTag;
}
/**
* Sets whether the tag should be a branch tag.
*/
public void setMakeBranchTag(boolean makeBranchTag) {
this.makeBranchTag = makeBranchTag;
}
/**
* Returns true to indicate that existing tag will be overridden.
*/
public boolean isOverrideExistingTag() {
return overrideExistingTag;
}
/**
* Sets whether existing tags should be overridden.
*/
public void setOverrideExistingTag(boolean overrideExistingTag) {
this.overrideExistingTag = overrideExistingTag;
}
public boolean isMatchHeadIfRevisionNotFound() {
return matchHeadIfRevisionNotFound;
}
public void setMatchHeadIfRevisionNotFound(boolean matchHeadIfRevisionNotFound) {
this.matchHeadIfRevisionNotFound = matchHeadIfRevisionNotFound;
}
public boolean isNoExecTagProgram() {
return noExecTagProgram;
}
public void setNoExecTagProgram(boolean noExecTagProgram) {
this.noExecTagProgram = noExecTagProgram;
}
/**
* Returns the tag that should be added or deleted.
*/
public String getTag() {
return tag;
}
/**
* Sets the tag that should be added or deleted.
*/
public void setTag(String tag) {
this.tag = tag;
}
/**
* Returns the latest date of a revision to be tagged.
* @return date value. the latest Revision not later ten date is tagged.
*/
public String getTagByDate() {
return tagByDate;
}
/**
* Sets the latest date of a revision to be tagged.
* @param tagDate New value of property tagDate.
*/
public void setTagByDate(String tagDate) {
tagByDate = tagDate;
}
/**
* Sets the latest date of a revision to be tagged. Can be both a number and a tag.
* @return Value of property tagRevision.
*/
public String getTagByRevision() {
return tagByRevision;
}
/**
* Sets the latest date of a revision to be tagged. Can be both a number and a tag.
* @param tagRevision New value of property tagRevision.
*/
public void setTagByRevision(String tagRevision) {
tagByRevision = tagRevision;
}
/**
* Execute the command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests.
*/
protected void postExpansionExecute(ClientServices client, EventManager eventManager)
throws CommandException, AuthenticationException {
client.ensureConnection();
this.eventManager = eventManager;
try {
if (clearFromRemoved) {
requests.add(new ArgumentRequest("-a")); //NOI18N
}
if (overrideExistingTag) {
requests.add(new ArgumentRequest("-F")); //NOI18N
}
if (matchHeadIfRevisionNotFound) {
requests.add(new ArgumentRequest("-f")); // NOI18N
}
if (makeBranchTag) {
requests.add(new ArgumentRequest("-b")); //NOI18N
}
if (deleteTag) {
requests.add(new ArgumentRequest("-d")); //NOI18N
}
if (noExecTagProgram) {
requests.add(new ArgumentRequest("-n ")); // NOI18N
}
if (tagByDate != null && tagByDate.length() > 0) {
requests.add(new ArgumentRequest("-D")); //NOI18N
requests.add(new ArgumentRequest(getTagByDate()));
}
if (tagByRevision != null && tagByRevision.length() > 0) {
requests.add(new ArgumentRequest("-r")); //NOI18N
requests.add(new ArgumentRequest(getTagByRevision()));
}
requests.add(new ArgumentRequest(getTag()));
//addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.RTAG);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
throw new CommandException(ex, CommandException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* Called when server responses with "ok" or "error", (when the command
* finishes).
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* This method returns how the tag command would looklike when typed on the
* command line.
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("rtag "); //NOI18N
toReturn.append(getCVSArguments());
if (getTag() != null) {
toReturn.append(getTag());
toReturn.append(" "); //NOI18N
}
appendModuleArguments(toReturn);
return toReturn.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'a') {
setClearFromRemoved(true);
}
else if (opt == 'd') {
setDeleteTag(true);
}
else if (opt == 'F') {
setOverrideExistingTag(true);
}
else if (opt == 'f') {
setMatchHeadIfRevisionNotFound(true);
}
else if (opt == 'b') {
setMakeBranchTag(true);
}
else if (opt == 'n') {
setNoExecTagProgram(true);
}
else if (opt == 'D') {
setTagByDate(optArg.trim());
}
else if (opt == 'r') {
setTagByRevision(optArg.trim());
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for
* this command.
*/
public String getOptString() {
return "RlaFfbdnD:r:"; //NOI18N
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setClearFromRemoved(false);
setDeleteTag(false);
setMakeBranchTag(false);
setOverrideExistingTag(false);
setMatchHeadIfRevisionNotFound(false);
setNoExecTagProgram(false);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer();
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (isClearFromRemoved()) {
toReturn.append("-a "); //NOI18N
}
if (isOverrideExistingTag()) {
toReturn.append("-F "); //NOI18N
}
if (isMatchHeadIfRevisionNotFound()) {
toReturn.append("-f ");
}
if (isMakeBranchTag()) {
toReturn.append("-b "); //NOI18N
}
if (isDeleteTag()) {
toReturn.append("-d "); //NOI18N
}
if (isNoExecTagProgram()) {
toReturn.append("-n "); // NOI18N
}
if (getTagByRevision() != null && getTagByRevision().length() > 0) {
toReturn.append("-r "); //NOI18N
toReturn.append(getTagByRevision());
toReturn.append(" "); //NOI18N
}
if (getTagByDate() != null && getTagByDate().length() > 0) {
toReturn.append("-D "); //NOI18N
toReturn.append(getTagByDate());
toReturn.append(" "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/tag/TagBuilder.java 0000644 0001753 0000144 00000010401 11175407000 027104 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.tag;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* @author Thomas Singer
*/
public class TagBuilder
implements Builder {
public static final String STATES = "T D ? "; //NOI18N
public static final String CVS_SERVER = "server: "; //NOI18N
public static final String EXAM_DIR = "server: "; //NOI18N
/**
* The status object that is currently being built.
*/
private DefaultFileInfoContainer fileInfoContainer;
/**
* The event manager to use.
*/
private EventManager eventManager;
/**
* The local path the command run in.
*/
private String localPath;
public TagBuilder(EventManager eventManager, String localPath) {
this.eventManager = eventManager;
this.localPath = localPath;
}
public void outputDone() {
if (fileInfoContainer != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, fileInfoContainer));
fileInfoContainer = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (isErrorMessage) {
return;
}
if (line.indexOf(CVS_SERVER) < 0) {
if (line.length() < 3) {
return;
}
String firstChar = line.substring(0, 2);
if (STATES.indexOf(firstChar) >= 0) {
processFile(line);
}
}
}
private void processFile(String line) {
if (fileInfoContainer == null) {
fileInfoContainer = new DefaultFileInfoContainer();
}
fileInfoContainer.setType(line.substring(0, 1));
String fileName = line.substring(2).trim();
if (fileName.startsWith("no file")) { //NOI18N
fileName = fileName.substring(8);
}
fileInfoContainer.setFile(createFile(fileName));
eventManager.fireCVSEvent(new FileInfoEvent(this, fileInfoContainer));
fileInfoContainer = null;
}
private File createFile(String fileName) {
return new File(localPath, fileName);
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/tag/TagCommand.java 0000644 0001753 0000144 00000031643 11175407000 027107 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Thomas Singer.
* Portions created by Robert Greig are Copyright (C) 2001.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Thomas Singer.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.tag;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The tag command adds or deleted a tag to the specified files/directories.
*
* @author Thomas Singer
*/
public class TagCommand extends BasicCommand {
/**
* The event manager to use.
*/
private EventManager eventManager;
private boolean checkThatUnmodified;
private boolean deleteTag;
private boolean makeBranchTag;
private boolean overrideExistingTag;
private boolean matchHeadIfRevisionNotFound;
private String tag;
private String tagByDate;
private String tagByRevision;
/**
* Construct a new tag command.
*/
public TagCommand() {
}
/**
* Creates the TagBuilder.
* @param eventManager the event manager used to received cvs events
*/
public Builder createBuilder(EventManager eventManager) {
return new TagBuilder(eventManager, getLocalDirectory());
}
/**
* Returns true if checking for unmodified files is enabled.
* @deprecated
*/
public boolean doesCheckThatUnmodified() {
return checkThatUnmodified;
}
/**
* Returns true if checking for unmodified files is enabled.
*/
public boolean isCheckThatUnmodified() {
return checkThatUnmodified;
}
/**
* Enabled the check for unmodified files.
*/
public void setCheckThatUnmodified(boolean checkThatUnmodified) {
this.checkThatUnmodified = checkThatUnmodified;
}
/**
* Returnes true if the tag should be deleted (otherwise added).
* @deprecated
*/
public boolean doesDeleteTag() {
return deleteTag;
}
/**
* Returnes true if the tag should be deleted (otherwise added).
*/
public boolean isDeleteTag() {
return deleteTag;
}
/**
* Sets whether the tag should be deleted (true) or added (false).
*/
public void setDeleteTag(boolean deleteTag) {
this.deleteTag = deleteTag;
}
/**
* Returns true if the tag should be a branch tag.
* @deprecated
*/
public boolean doesMakeBranchTag() {
return makeBranchTag;
}
/**
* Returns true if the tag should be a branch tag.
*/
public boolean isMakeBranchTag() {
return makeBranchTag;
}
/**
* Sets whether the tag should be a branch tag.
*/
public void setMakeBranchTag(boolean makeBranchTag) {
this.makeBranchTag = makeBranchTag;
}
/**
* Returns true to indicate that existing tag will be overridden.
* @deprecated
*/
public boolean doesOverrideExistingTag() {
return overrideExistingTag;
}
/**
* Returns true to indicate that existing tag will be overridden.
*/
public boolean isOverrideExistingTag() {
return overrideExistingTag;
}
/**
* Sets whether existing tags should be overridden.
*/
public void setOverrideExistingTag(boolean overrideExistingTag) {
this.overrideExistingTag = overrideExistingTag;
}
public boolean isMatchHeadIfRevisionNotFound() {
return matchHeadIfRevisionNotFound;
}
public void setMatchHeadIfRevisionNotFound(boolean matchHeadIfRevisionNotFound) {
this.matchHeadIfRevisionNotFound = matchHeadIfRevisionNotFound;
}
/**
* Returns the tag that should be added or deleted.
*/
public String getTag() {
return tag;
}
/**
* Sets the tag that should be added or deleted.
*/
public void setTag(String tag) {
this.tag = tag;
}
/**
* Returns the latest date of a revision to be tagged.
* @return date value. the latest Revision not later ten date is tagged.
*/
public String getTagByDate() {
return tagByDate;
}
/**
* Sets the latest date of a revision to be tagged.
* @param tagDate New value of property tagDate.
*/
public void setTagByDate(String tagDate) {
tagByDate = tagDate;
}
/**
* Sets the latest date of a revision to be tagged. Can be both a number and a tag.
* @return Value of property tagRevision.
*/
public String getTagByRevision() {
return tagByRevision;
}
/**
* Sets the latest date of a revision to be tagged. Can be both a number and a tag.
* @param tagRevision New value of property tagRevision.
*/
public void setTagByRevision(String tagRevision) {
tagByRevision = tagRevision;
}
/**
* Execute the command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests.
*/
public void execute(ClientServices client, EventManager eventManager)
throws CommandException, AuthenticationException {
client.ensureConnection();
this.eventManager = eventManager;
super.execute(client, eventManager);
try {
requests.add(1, new ArgumentRequest(getTag()));
if (checkThatUnmodified) {
requests.add(1, new ArgumentRequest("-c")); //NOI18N
}
if (overrideExistingTag) {
requests.add(1, new ArgumentRequest("-F")); //NOI18N
}
if (matchHeadIfRevisionNotFound) {
requests.add(1, new ArgumentRequest("-f")); // NOI18N
}
if (makeBranchTag) {
requests.add(1, new ArgumentRequest("-b")); //NOI18N
}
if (deleteTag) {
requests.add(1, new ArgumentRequest("-d")); //NOI18N
}
if (tagByDate != null && tagByDate.length() > 0) {
requests.add(1, new ArgumentRequest("-D")); //NOI18N
requests.add(2, new ArgumentRequest(getTagByDate()));
}
if (tagByRevision != null && tagByRevision.length() > 0) {
requests.add(1, new ArgumentRequest("-r")); //NOI18N
requests.add(2, new ArgumentRequest(getTagByRevision()));
}
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.TAG);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
throw new CommandException(ex, CommandException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* Called when server responses with "ok" or "error", (when the command
* finishes).
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* This method returns how the tag command would looklike when typed on the
* command line.
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("tag "); //NOI18N
toReturn.append(getCVSArguments());
if (getTag() != null) {
toReturn.append(getTag());
toReturn.append(" "); //NOI18N
}
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'c') {
setCheckThatUnmodified(true);
}
else if (opt == 'd') {
setDeleteTag(true);
}
else if (opt == 'F') {
setOverrideExistingTag(true);
}
else if (opt == 'f') {
setMatchHeadIfRevisionNotFound(true);
}
else if (opt == 'b') {
setMakeBranchTag(true);
}
else if (opt == 'D') {
setTagByDate(optArg.trim());
}
else if (opt == 'r') {
setTagByRevision(optArg.trim());
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for
* this command.
*/
public String getOptString() {
return "RlcFfbdD:r:"; //NOI18N
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setCheckThatUnmodified(false);
setDeleteTag(false);
setMakeBranchTag(false);
setOverrideExistingTag(false);
setMatchHeadIfRevisionNotFound(false);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer();
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (isCheckThatUnmodified()) {
toReturn.append("-c "); //NOI18N
}
if (isOverrideExistingTag()) {
toReturn.append("-F "); //NOI18N
}
if (isMatchHeadIfRevisionNotFound()) {
toReturn.append("-f ");
}
if (isMakeBranchTag()) {
toReturn.append("-b "); //NOI18N
}
if (isDeleteTag()) {
toReturn.append("-d "); //NOI18N
}
if (getTagByRevision() != null && getTagByRevision().length() > 0) {
toReturn.append("-r "); //NOI18N
toReturn.append(getTagByRevision());
toReturn.append(" "); //NOI18N
}
if (getTagByDate() != null && getTagByDate().length() > 0) {
toReturn.append("-D "); //NOI18N
toReturn.append(getTagByDate());
toReturn.append(" "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/unedit/ 0000755 0001753 0000144 00000000000 11175434236 024753 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/unedit/UneditCommand.java 0000644 0001753 0000144 00000020007 11175407000 030331 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.unedit;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.command.edit.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.file.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* @author Thomas Singer
*/
public class UneditCommand extends BasicCommand {
private Watch temporaryWatch;
/**
* Construct a new editors command.
*/
public UneditCommand() {
resetCVSCommand();
}
/**
* Execute the command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests.
*/
public void execute(ClientServices clientServices, EventManager eventManager)
throws CommandException, AuthenticationException {
clientServices.ensureConnection();
try {
super.execute(clientServices, eventManager);
addRequestForWorkingDirectory(clientServices);
addRequest(CommandRequest.NOOP);
clientServices.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
throw new CommandException(ex, CommandException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
protected void addRequestForFile(File file, Entry entry) {
String temporaryWatch = Watch.getWatchString(getTemporaryWatch());
requests.add(new NotifyRequest(file, "U", temporaryWatch)); // NOI18N
try {
uneditFile(file);
}
catch (IOException ex) {
// ignore
}
}
/**
* Called when server responses with "ok" or "error", (when the command
* finishes).
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* This method returns how the tag command would looklike when typed on the
* command line.
*/
public String getCVSCommand() {
StringBuffer cvsCommandLine = new StringBuffer("unedit "); //NOI18N
cvsCommandLine.append(getCVSArguments());
appendFileArguments(cvsCommandLine);
return cvsCommandLine.toString();
}
/**
* Takes the arguments and sets the command.
* To be mainly used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for
* this command.
*/
public String getOptString() {
return "Rl"; //NOI18N
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer cvsArguments = new StringBuffer();
if (!isRecursive()) {
cvsArguments.append("-l "); //NOI18N
}
return cvsArguments.toString();
}
/**
* Returns the temporary watch.
*/
public Watch getTemporaryWatch() {
return temporaryWatch;
}
/**
* Sets the temporary watch.
*/
public void setTemporaryWatch(Watch temporaryWatch) {
this.temporaryWatch = temporaryWatch;
}
private void uneditFile(File file) throws IOException {
removeBaserevEntry(file);
EditCommand.getEditBackupFile(file).delete();
FileUtils.setFileReadOnly(file, true);
}
private void removeBaserevEntry(File file) throws IOException {
File baserevFile = new File(file.getParentFile(), "CVS/Baserev"); // NOI18N
File backupFile = new File(baserevFile.getAbsolutePath() + '~');
BufferedReader reader = null;
BufferedWriter writer = null;
final String entryStart = 'B' + file.getName() + '/';
try {
writer = new BufferedWriter(new FileWriter(backupFile));
reader = new BufferedReader(new FileReader(baserevFile));
for (String line = reader.readLine();
line != null;
line = reader.readLine()) {
if (line.startsWith(entryStart)) {
continue;
}
writer.write(line);
writer.newLine();
}
}
catch (FileNotFoundException ex) {
// ignore
}
finally {
if (writer != null) {
try {
writer.close();
}
catch (IOException ex) {
// ignore
}
}
if (reader != null) {
try {
reader.close();
}
catch (IOException ex) {
// ignore
}
}
}
baserevFile.delete();
if (backupFile.length() > 0) {
backupFile.renameTo(baserevFile);
}
else {
backupFile.delete();
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/update/ 0000755 0001753 0000144 00000000000 11175434236 024745 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/update/UpdateBuilder.java 0000644 0001753 0000144 00000026355 11175407000 030341 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.update;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* Handles the building of update information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint, Thomas Singer
*/
public class UpdateBuilder
implements Builder {
/**
* Parsing constants..
*/
public static final String UNKNOWN = ": nothing known about"; //NOI18N
public static final String EXAM_DIR = ": Updating"; //NOI18N
public static final String TO_ADD = ": use `cvs add' to create an entry for"; //NOI18N
public static final String STATES = "U P A R M C ? "; //NOI18N
public static final String WARNING = ": warning: "; //NOI18N
public static final String SERVER = "server: "; //NOI18N
public static final String PERTINENT = "is not (any longer) pertinent"; //NOI18N
public static final String REMOVAL = "for removal"; //NOI18N
public static final String SERVER_SCHEDULING = "server: scheduling"; //NOI18N
private static final String SERVER_SCHEDULING_12 = "update: scheduling `"; //NOI18N
private static final String REMOVAL_12 = "' for removal"; //NOI18N
public static final String CONFLICTS = "rcsmerge: warning: conflicts during merge"; //NOI18N
public static final String NOT_IN_REPOSITORY = "is no longer in the repository"; //NOI18N;
//cotacao/src/client/net/riobranco/common/client/gui/BaseDialogThinlet.java already contains the differences between 1.17 and 1.18
private static final String MERGE_SAME = " already contains the differences between";
private static final String MERGED = "Merging differences between"; //NOI18N;
/**
* The status object that is currently being built.
*/
private DefaultFileInfoContainer fileInfoContainer;
/**
* The event manager to use.
*/
private EventManager eventManager;
/**
* The local path the command run in.
*/
private final String localPath;
private String diagnostics;
/**
* Holds 'G' or 'C' if the current file was merged or conflicted, respectively.
*/
private String fileMergedOrConflict;
public UpdateBuilder(EventManager eventManager, String localPath) {
this.eventManager = eventManager;
this.localPath = localPath;
}
public void outputDone() {
fileMergedOrConflict = null;
if (fileInfoContainer != null) {
if (fileInfoContainer.getFile() == null) {
System.err.println("#65387 CVS: firing invalid event while processing: " + diagnostics);
}
eventManager.fireCVSEvent(new FileInfoEvent(this, fileInfoContainer));
fileInfoContainer = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
diagnostics = line;
if (line.indexOf(UNKNOWN) >= 0) {
processUnknownFile(line, line.indexOf(UNKNOWN) + UNKNOWN.length());
}
else if (line.indexOf(TO_ADD) >= 0) {
processUnknownFile(line, line.indexOf(TO_ADD) + TO_ADD.length());
}
else if (line.indexOf(EXAM_DIR) >= 0) { // never comes with :local; connection method
return;
}
else if (line.startsWith(CONFLICTS)) {
if (fileInfoContainer != null) {
fileInfoContainer.setType("C"); //NOI18N
// fire from Merged response which follows
}
fileMergedOrConflict = "C";
}
else if (line.indexOf(WARNING) >= 0) {
if (line.indexOf(PERTINENT) > 0) {
String filename = line.substring(line.indexOf(WARNING) + WARNING.length(),
line.indexOf(PERTINENT)).trim();
processNotPertinent(filename);
}
}
else if (line.indexOf(SERVER_SCHEDULING_12) >= 0) {
if (line.indexOf(REMOVAL_12) > 0) {
String filename = line.substring(line.indexOf(SERVER_SCHEDULING_12) + SERVER_SCHEDULING_12.length(),
line.indexOf(REMOVAL_12)).trim();
processNotPertinent(filename);
}
}
else if (line.indexOf(SERVER_SCHEDULING) >= 0) {
if (line.indexOf(REMOVAL) > 0) {
String filename = line.substring(line.indexOf(SERVER_SCHEDULING) + SERVER_SCHEDULING.length(),
line.indexOf(REMOVAL)).trim();
processNotPertinent(filename);
}
}
else if (line.indexOf(MERGE_SAME) >= 0) { // not covered by parseEnhancedMessage
ensureExistingFileInfoContainer();
fileInfoContainer.setType(DefaultFileInfoContainer.MERGED_FILE);
String path = line.substring(0, line.indexOf(MERGE_SAME));
fileInfoContainer.setFile(createFile(path));
outputDone();
}
else if (line.startsWith(MERGED)) { // not covered by parseEnhancedMessage
outputDone();
fileMergedOrConflict = "G";
}
else if (line.indexOf(NOT_IN_REPOSITORY) > 0) {
String filename = line.substring(line.indexOf(SERVER) + SERVER.length(),
line.indexOf(NOT_IN_REPOSITORY)).trim();
processNotPertinent(filename);
return;
}
else {
// otherwise
if (line.length() > 2) {
String firstChar = line.substring(0, 2);
if (STATES.indexOf(firstChar) >= 0) {
processFile(line);
return;
}
}
}
}
private File createFile(String fileName) {
if (fileName.length() > 1 && fileName.charAt(0) == '`' && fileName.charAt(fileName.length() - 1) == '\'') {
fileName = fileName.substring(1, fileName.length() - 1);
}
return new File(localPath, fileName);
}
private void ensureExistingFileInfoContainer() {
if (fileInfoContainer != null) {
return;
}
fileInfoContainer = new DefaultFileInfoContainer();
}
private void processUnknownFile(String line, int index) {
outputDone();
fileInfoContainer = new DefaultFileInfoContainer();
fileInfoContainer.setType("?"); //NOI18N
String fileName = (line.substring(index)).trim();
fileInfoContainer.setFile(createFile(fileName));
}
private void processFile(String line) {
String fileName = line.substring(2).trim();
if (fileName.startsWith("no file")) { //NOI18N
fileName = fileName.substring(8);
}
if (fileName.startsWith("./")) { //NOI18N
fileName = fileName.substring(2);
}
File file = createFile(fileName);
if (fileInfoContainer != null) {
// sometimes (when locally modified.. the merged response is followed by mesage M or C ..
// check the file.. if equals.. it's the same one.. don't send again.. the prior type has preference
if (fileInfoContainer.getFile() == null) {
// is null in case the global switch -n is used - then no Enhanced message is sent, and no
// file is assigned the merged file..
fileInfoContainer.setFile(file);
}
if (file.equals(fileInfoContainer.getFile())) {
// if the previous information does not say anything, prefer newer one
if (fileInfoContainer.getType().equals("?")) {
fileInfoContainer = null;
} else {
outputDone();
return;
}
}
}
if (fileMergedOrConflict != null && line.charAt(0) == 'M') {
line = fileMergedOrConflict; // can be done this way, see below
}
outputDone();
ensureExistingFileInfoContainer();
fileInfoContainer.setType(line.substring(0, 1));
fileInfoContainer.setFile(file);
}
private void processNotPertinent(String fileName) {
outputDone();
File fileToDelete = createFile(fileName);
ensureExistingFileInfoContainer();
// HACK - will create a non-cvs status in order to be able to have consistent info format
fileInfoContainer.setType(DefaultFileInfoContainer.PERTINENT_STATE);
fileInfoContainer.setFile(fileToDelete);
}
/** Merged response handler. */
public void parseEnhancedMessage(String key, Object value) {
if (key.equals(EnhancedMessageEvent.MERGED_PATH)) {
ensureExistingFileInfoContainer();
String path = value.toString();
File newFile = new File(path);
// #70106 Merged responce must not rewrite CONFLICTS
if (newFile.equals(fileInfoContainer.getFile()) == false) {
fileInfoContainer.setFile(newFile);
fileInfoContainer.setType(DefaultFileInfoContainer.MERGED_FILE);
if (fileMergedOrConflict != null) {
fileInfoContainer.setType(fileMergedOrConflict);
}
}
outputDone();
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/update/UpdateCommand.java 0000644 0001753 0000144 00000060625 11175407000 030327 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.command.update;
import java.io.*;
import java.text.*;
import java.util.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.file.FileUtils;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The Update command. Updates files that have previously been checked out
* from the repository with the checkout command. Modified files are not
* overwritten.
* @author Robert Greig
*/
public class UpdateCommand extends BasicCommand
implements TemporaryFileCreator {
// This format possibly may be set by the user of the library later.
private static final String RENAME_FORMAT = "{0}/.#{1}.{2}"; //NOI18N
private static final Object[] FORMAT_PARAMETER = new Object[3]; // { path, filename, revision }
/**
* A store of potentially empty directories. When a directory has a file
* in it, it is removed from this set. This set allows the prune option
* to be implemented.
*/
private final Set emptyDirectories = new HashSet();
/**
* Whether to build directories, like checkout does (this is the -d option
* in command-line CVS).
*/
private boolean buildDirectories;
/**
* Determines whether to get a clean copy from the server.
* This overrides even locally modified files.
*/
private boolean cleanCopy;
/**
* Whether to prune directories, i.e. remove any directories that do not
* contain any files. This is the -P option in command-line CVS).
*/
private boolean pruneDirectories;
/**
* Determines wheather the output of the command is processed on standard output.
* Default is false. If true, nothing is done to local working files.
*/
private boolean pipeToOutput;
/**
* Resets any sticky tags/dates/options imposed on the updated file(s).
*/
private boolean resetStickyOnes;
/**
* Use head revision if a revision meeting criteria set by switches -r/-D
* (tag/date) is not found.
*/
private boolean useHeadIfNotFound;
/**
* equals the -D switch of command line cvs.
*/
private String updateByDate;
/**
* Equals the -r switch of command-line cvs.
*/
private String updateByRevision;
/**
* Use this keyword substitution for the command.
* does not include the -k switch part.
*/
private KeywordSubstitutionOptions keywordSubst;
/**
* First of the 2 possible -j switches that merge 2 different revisions.
* If only this property is set, the current working file is merged
* with the specified one.
*/
private String mergeRevision1;
/**
* Second of the 2 possible -j switches that merge 2 different revisions.
* Assumes the first -j switch (mergeRevision1 property) is set.
* Then the update commands merges the sources of these 2 revisons specified
* by the -j switches.
*/
private String mergeRevision2;
/**
* Construct a new update command.
*/
public UpdateCommand() {
// TODO: move up the hierarchy ?
resetCVSCommand();
}
/**
* Method that is called while the command is being executed.
* Descendants can override this method to return a Builder instance
* that will parse the server's output and create data structures.
*/
public Builder createBuilder(EventManager eventManager) {
if (isPipeToOutput()) {
return new PipedFilesBuilder(eventManager, this, this);
}
return new UpdateBuilder(eventManager, getLocalDirectory());
}
/**
* If getCleanCopy()
returns true, the files will be treated
* as not existing.
*/
protected void sendEntryAndModifiedRequests(Entry entry, File file) {
if (isCleanCopy() && file != null && entry != null) {
if (!isPipeToOutput()) {
FORMAT_PARAMETER[0] = file.getParent();
FORMAT_PARAMETER[1] = file.getName();
FORMAT_PARAMETER[2] = entry.getRevision();
String filename = MessageFormat.format(RENAME_FORMAT, FORMAT_PARAMETER);
try {
FileUtils.copyFile(file, new File(filename));
} catch (IOException e) {
// backup copy will not be created
}
}
file = null;
}
super.sendEntryAndModifiedRequests(entry, file);
}
/**
* Set whether to build directories. This is the -d option in command-line
* CVS.
*/
public void setBuildDirectories(boolean buildDirectories) {
this.buildDirectories = buildDirectories;
}
/**
* Returns whether to build directories.
* @return true if directories are to be built, false otherwise
*/
public boolean isBuildDirectories() {
return buildDirectories;
}
/**
* Sets whether to get a clean copy from the server.
* Even locally modified files will not merged but overridden.
* This is the -C option in the command-line CVS.
*/
public void setCleanCopy(boolean cleanCopy) {
this.cleanCopy = cleanCopy;
}
/**
* Returns whether to get a clean copy from the server.
*/
public boolean isCleanCopy() {
return cleanCopy;
}
/**
* Set whether to prune directories. This is the -P option in the command-
* line CVS.
*/
public void setPruneDirectories(boolean pruneDirectories) {
this.pruneDirectories = pruneDirectories;
}
/**
* Returns whether to prune directories.
* @return true if directories should be removed if they contain no files,
* false otherwise.
*/
public boolean isPruneDirectories() {
return pruneDirectories;
}
/**
* Execute the command.
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests
*/
public void execute(ClientServices client, EventManager eventManager)
throws CommandException, AuthenticationException {
client.ensureConnection();
super.execute(client, eventManager);
emptyDirectories.clear();
try {
// now add the request that indicates the working directory for the
// command
if (!isRecursive()) {
requests.add(1, new ArgumentRequest("-l")); //NOI18N
}
if (isBuildDirectories()) {
requests.add(1, new ArgumentRequest("-d")); //NOI18N
}
if (isCleanCopy() && !isPipeToOutput()) {
requests.add(1, new ArgumentRequest("-C")); //NOI18N
}
if (isPipeToOutput()) {
requests.add(1, new ArgumentRequest("-p")); //NOI18N
}
if (isResetStickyOnes()) {
requests.add(1, new ArgumentRequest("-A")); //NOI18N
}
if (isUseHeadIfNotFound()) {
requests.add(1, new ArgumentRequest("-f")); //NOI18N
}
if (getUpdateByDate() != null) {
requests.add(1, new ArgumentRequest("-D")); //NOI18N
requests.add(2, new ArgumentRequest(getUpdateByDate()));
}
else if (getUpdateByRevision() != null) {
requests.add(1, new ArgumentRequest("-r")); //NOI18N
requests.add(2, new ArgumentRequest(getUpdateByRevision()));
}
if (getMergeRevision1() != null) {
requests.add(1, new ArgumentRequest("-j")); //NOI18N
requests.add(2, new ArgumentRequest(getMergeRevision1()));
if (getMergeRevision2() != null) {
requests.add(3, new ArgumentRequest("-j")); //NOI18N
requests.add(4, new ArgumentRequest(getMergeRevision2()));
}
}
if (getKeywordSubst() != null) {
requests.add(1, new ArgumentRequest("-k")); //NOI18N
requests.add(2, new ArgumentRequest(getKeywordSubst().toString()));
}
requests.add(1, new ArgumentRequest("-u")); //NOI18N
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.UPDATE);
// hack - now check for the entry request for removed files
// only when p with -r or -D is on
if (isPipeToOutput() && (getUpdateByRevision() != null || getUpdateByDate() != null)) {
ListIterator it = requests.listIterator();
while (it.hasNext()) {
Object req = it.next();
if (req instanceof EntryRequest) {
EntryRequest eReq = (EntryRequest)req;
Entry entry = eReq.getEntry();
if (entry.getRevision().startsWith("-")) {//NOI18N
entry.setRevision(entry.getRevision().substring(1));
}
it.set(new EntryRequest(entry));
it.add(new UnchangedRequest(entry.getName()));
}
}
}
// end of hack..
client.processRequests(requests);
if (pruneDirectories && (getGlobalOptions() == null || !getGlobalOptions().isDoNoChanges())) {
pruneEmptyDirectories(client);
}
}
catch (CommandException ex) {
throw ex;
}
catch (EOFException ex) {
throw new CommandException(ex, CommandException.getLocalMessage("CommandException.EndOfFile", null)); //NOI18N
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* Getter for property pipeToOutput.
* @return Value of property pipeToOutput.
*/
public boolean isPipeToOutput() {
return pipeToOutput;
}
/**
* Setter for property pipeToOutput.
* @param pipeToOutput New value of property pipeToOutput.
*/
public void setPipeToOutput(boolean pipeToOutput) {
this.pipeToOutput = pipeToOutput;
}
/**
* Getter for property resetStickyOnes.
* @return Value of property resetStickyOnes.
*/
public boolean isResetStickyOnes() {
return resetStickyOnes;
}
/**
* Setter for property resetStickyOnes.
* @param resetStickyOnes New value of property resetStickyOnes.
*/
public void setResetStickyOnes(boolean resetStickyOnes) {
this.resetStickyOnes = resetStickyOnes;
}
/**
* Getter for property useHeadIfNotFound.
* @return Value of property useHeadIfNotFound.
*/
public boolean isUseHeadIfNotFound() {
return useHeadIfNotFound;
}
/**
* Setter for property useHeadIfNotFound.
* @param useHeadIfNotFound New value of property useHeadIfNotFound.
*/
public void setUseHeadIfNotFound(boolean useHeadIfNotFound) {
this.useHeadIfNotFound = useHeadIfNotFound;
}
/**
* Getter for property updateByDate.
* @return Value of property updateByDate.
*/
public String getUpdateByDate() {
return updateByDate;
}
/**
* Setter for property updateByDate.
* @param updateByDate New value of property updateByDate.
*/
public void setUpdateByDate(String updateByDate) {
this.updateByDate = getTrimmedString(updateByDate);
}
/**
* Getter for property updateByRevision.
* @return Value of property updateByRevision.
*/
public String getUpdateByRevision() {
return updateByRevision;
}
/**
* Setter for property updateByRevision.
* @param updateByRevision New value of property updateByRevision.
*/
public void setUpdateByRevision(String updateByRevision) {
this.updateByRevision = getTrimmedString(updateByRevision);
}
/**
* Getter for property keywordSubst.
* @return Value of property keywordSubst.
*/
public KeywordSubstitutionOptions getKeywordSubst() {
return keywordSubst;
}
/**
* Setter for property keywordSubst.
* @param keywordSubst New value of property keywordSubst.
*/
public void setKeywordSubst(KeywordSubstitutionOptions keywordSubst) {
this.keywordSubst = keywordSubst;
}
/**
* Method that creates a temporary file.
*/
public File createTempFile(String filename) throws IOException {
File temp = File.createTempFile("cvs", ".dff", getGlobalOptions().getTempDir()); //NOI18N
temp.deleteOnExit();
return temp;
}
/**
* This method returns how the command would looklike when typed on the
* command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs.
* Example: checkout -p CvsCommand.java
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("update "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer(""); //NOI18N
if (isPipeToOutput()) {
toReturn.append("-p "); //NOI18N
}
if (isCleanCopy()) {
toReturn.append("-C "); //NOI18N
}
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
if (isBuildDirectories()) {
toReturn.append("-d "); //NOI18N
}
if (isPruneDirectories()) {
toReturn.append("-P "); //NOI18N
}
if (isResetStickyOnes()) {
toReturn.append("-A "); //NOI18N
}
if (isUseHeadIfNotFound()) {
toReturn.append("-f "); //NOI18N
}
if (getKeywordSubst() != null) {
toReturn.append("-k"); //NOI18N
toReturn.append(getKeywordSubst().toString());
toReturn.append(' ');
}
if (getUpdateByRevision() != null) {
toReturn.append("-r "); //NOI18N
toReturn.append(getUpdateByRevision());
toReturn.append(' ');
}
if (getUpdateByDate() != null) {
toReturn.append("-D "); //NOI18N
toReturn.append(getUpdateByDate());
toReturn.append(' ');
}
if (getMergeRevision1() != null) {
toReturn.append("-j "); //NOI18N
toReturn.append(getMergeRevision1());
toReturn.append(' ');
if (getMergeRevision2() != null) {
toReturn.append("-j "); //NOI18N
toReturn.append(getMergeRevision2());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* Takes the arguments and by parsing them, sets the command. To be mainly
* used for automatic settings (like parsing the .cvsrc file)
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'C') {
setCleanCopy(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else if (opt == 'd') {
setBuildDirectories(true);
}
else if (opt == 'P') {
setPruneDirectories(true);
}
else if (opt == 'A') {
setResetStickyOnes(true);
}
else if (opt == 'f') {
setUseHeadIfNotFound(true);
}
else if (opt == 'D') {
setUpdateByDate(optArg.trim());
}
else if (opt == 'r') {
setUpdateByRevision(optArg.trim());
}
else if (opt == 'k') {
KeywordSubstitutionOptions keywordSubst =
KeywordSubstitutionOptions.findKeywordSubstOption(optArg);
setKeywordSubst(keywordSubst);
}
else if (opt == 'p') {
setPipeToOutput(true);
}
else if (opt == 'j') {
if (getMergeRevision1() == null) {
setMergeRevision1(optArg);
}
else {
setMergeRevision2(optArg);
}
}
else {
// TODO - now silently ignores not recognized switches.
return false;
}
return true;
}
/**
* Resets all switches in the command.
* After calling this method, the command should have no switches defined
* and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
setCleanCopy(false);
setBuildDirectories(false);
setPruneDirectories(false);
setResetStickyOnes(false);
setUseHeadIfNotFound(false);
setUpdateByDate(null);
setUpdateByRevision(null);
setKeywordSubst(null);
setPipeToOutput(false);
setMergeRevision1(null);
setMergeRevision2(null);
}
/**
* Called when the server wants to send a message to be displayed to
* the user. The message is only for information purposes and clients
* can choose to ignore these messages if they wish.
* @param e the event
*/
public void messageSent(MessageEvent e) {
super.messageSent(e);
// we use this event to determine which directories need to be checked
// for updating
if (!pruneDirectories) {
return;
}
final String relativePath = CommandUtils.getExaminedDirectory(e.getMessage(),
UpdateBuilder.EXAM_DIR);
if (relativePath == null) {
return;
}
// dont delete the current directory, even if it's empty
if (relativePath.equals(".")) { //NOI18N
return;
}
emptyDirectories.add(new File(getLocalDirectory(), relativePath));
}
/**
* Prunes a directory, recursively pruning its subdirectories
* @param directory the directory to prune
*/
private boolean pruneEmptyDirectory(File directory, ClientServices client)
throws IOException {
final File[] contents = directory.listFiles();
// should never be null, but just in case...
if (contents == null) {
return true;
}
for (int i = 0; i < contents.length; i++) {
if (contents[i].isFile()) {
return false;
}
// Skip the cvs directory
if (contents[i].getName().equals("CVS")) {
//NOI18N
continue;
}
if (!pruneEmptyDirectory(contents[i], client)) {
return false;
}
}
// check this is a CVS directory and not some directory the user
// has stupidly called CVS...
if (new File(directory, "CVS/Entries").isFile() && new File(directory, "CVS/Repository").isFile()) {
final File adminDir = new File(directory, "CVS"); //NOI18N
// we must NOT delete a directory if it contains valuable entries
for (Iterator i = clientServices.getEntries(directory); i.hasNext(); ) {
Entry entry = (Entry) i.next();
if (entry.getName() != null && entry.isUserFileToBeRemoved()) return false;
}
deleteRecursively(adminDir);
directory.delete();
// if the client still makes this directory's entries available, do not delete its entry
if (!client.exists(directory)) client.removeEntry(directory);
return true;
}
return false;
}
/**
* Deletes a directory and all files and directories inside the directory.
*
* @param dir directory to delete
*/
private void deleteRecursively(File dir) {
File [] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
deleteRecursively(file);
} else {
file.delete();
}
}
dir.delete();
}
/**
* Remove any directories that don't contain any files
*/
private void pruneEmptyDirectories(ClientServices client)
throws IOException {
for (Iterator it = emptyDirectories.iterator(); it.hasNext();) {
final File dir = (File)it.next();
// we might have deleted it already (due to recursive delete)
// so we need to check existence
if (dir.exists()) {
pruneEmptyDirectory(dir, client);
}
}
emptyDirectories.clear();
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "RCnldPAfD:r:pj:k:"; //NOI18N
}
/** Getter for property mergeRevision1.
* @return Value of property mergeRevision1.
*/
public String getMergeRevision1() {
return mergeRevision1;
}
/** Setter for property mergeRevision1.
* @param mergeRevision1 New value of property mergeRevision1.
*/
public void setMergeRevision1(String mergeRevision1) {
this.mergeRevision1 = getTrimmedString(mergeRevision1);
}
/** Getter for property mergeRevision2.
* @return Value of property mergeRevision2.
*/
public String getMergeRevision2() {
return mergeRevision2;
}
/** Setter for property mergeRevision2.
* @param mergeRevision2 New value of property mergeRevision2.
*/
public void setMergeRevision2(String mergeRevision2) {
this.mergeRevision2 = getTrimmedString(mergeRevision2);
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/watch/ 0000755 0001753 0000144 00000000000 11175434236 024571 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/watch/WatchCommand.java 0000644 0001753 0000144 00000016526 11175407000 030000 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.watch;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* @author Thomas Singer
*/
public class WatchCommand extends BasicCommand {
private WatchMode watchMode;
private Watch watch;
/**
* Construct a new WatchCommand.
*/
public WatchCommand() {
resetCVSCommand();
}
/**
* Executes this command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests
* @param eventManager the EventManager used for sending events
*
* @throws IllegalStateException if the commands options aren't set correctly
* @throws AuthenticationException if the connection could not be established
* @throws CommandException if some other thing gone wrong
*/
public void execute(ClientServices client, EventManager eventManager)
throws CommandException, AuthenticationException {
checkState();
client.ensureConnection();
try {
super.execute(client, eventManager);
if (getWatchMode().isWatchOptionAllowed()) {
String[] arguments = getWatchNotNull().getArguments();
for (int i = 0; i < arguments.length; i++) {
addRequest(new ArgumentRequest("-a")); // NOI18N
addRequest(new ArgumentRequest(arguments[i]));
}
}
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(getWatchMode().getCommand());
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* If a builder was set-up, it's outputDone() method is called.
* This method is called, when the server responses with "ok" or "error"
* (== when the command finishes).
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* Uses the specified argument to set the appropriate properties.
* To be mainly used for automatic settings (like parsing the .cvsrc file)
*
* @return whether the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for
* this command.
*/
public String getOptString() {
return "Rl"; //NOI18N
}
/**
* Resets all switches in this command.
* After calling this method, the command behaves like newly created.
*/
public void resetCVSCommand() {
setRecursive(true);
setWatch(null);
}
/**
* Returns how this command would look like when typed on the command line.
*/
public String getCVSCommand() {
StringBuffer cvsCommand = new StringBuffer("watch "); //NOI18N
cvsCommand.append(getCVSArguments());
appendFileArguments(cvsCommand);
return cvsCommand.toString();
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
checkState();
StringBuffer cvsArguments = new StringBuffer();
cvsArguments.append(getWatchMode().toString());
cvsArguments.append(' ');
if (!isRecursive()) {
cvsArguments.append("-l "); //NOI18N
}
if (getWatchMode().isWatchOptionAllowed()) {
cvsArguments.append("-a ");
cvsArguments.append(getWatchNotNull().toString());
}
return cvsArguments.toString();
}
/**
* Returns the WatchMode.
*/
public WatchMode getWatchMode() {
return watchMode;
}
/**
* Sets the WatchMode.
*/
public void setWatchMode(WatchMode watchMode) {
this.watchMode = watchMode;
}
/**
* Returns the watch.
*/
public Watch getWatch() {
return watch;
}
private Watch getWatchNotNull() {
if (watch == null) {
return Watch.ALL;
}
return watch;
}
/**
* Sets the watch.
* If the WatchMode ADD or REMOVE is used, null is the same as Watch.ALL.
* If the WatchMode ON or OFF is used, this option isn't used at all.
*/
public void setWatch(Watch watch) {
this.watch = watch;
}
private void checkState() {
if (getWatchMode() == null) {
throw new IllegalStateException("Watch mode expected!");
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/watch/WatchMode.java 0000644 0001753 0000144 00000010344 11175407000 027276 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.watch;
import org.netbeans.lib.cvsclient.request.*;
/**
* @author Thomas Singer
* @version Dec 29, 2001
*/
public class WatchMode {
/**
* This is the WatchMode that enables watching.
*/
public static final WatchMode ON = new WatchMode("on", // NOI18N
CommandRequest.WATCH_ON,
false);
/**
* This is the WatchMode that disables watching.
*/
public static final WatchMode OFF = new WatchMode("off", // NOI18N
CommandRequest.WATCH_OFF,
false);
/**
* This is the WatchMode that adds watching for the specified Watch.
*/
public static final WatchMode ADD = new WatchMode("add", // NOI18N
CommandRequest.WATCH_ADD,
true);
/**
* This is the WatchMode that removes watching for the specified Watch.
*/
public static final WatchMode REMOVE = new WatchMode("remove", // NOI18N
CommandRequest.WATCH_REMOVE,
true);
private final String name;
private final CommandRequest command;
private final boolean watchOptionAllowed;
private WatchMode(String name, CommandRequest command, boolean watchOptionAllowed) {
this.name = name;
this.command = command;
this.watchOptionAllowed = watchOptionAllowed;
}
/**
* Returns the CommandRequest that is used when executing the WatchCommand
* with this WatchMode.
*/
public CommandRequest getCommand() {
return command;
}
/**
* Indicated, whether a non-null watch-option is allowed in the WatchCommand.
*/
public boolean isWatchOptionAllowed() {
return watchOptionAllowed;
}
/**
* Returns the name of this WatchMode ("on", "off", "add", "remove").
*/
public String toString() {
return name;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/watchers/ 0000755 0001753 0000144 00000000000 11175434236 025303 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/watchers/WatchersBuilder.java 0000644 0001753 0000144 00000011117 11175407000 031223 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.watchers;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* Handles the building of a watchers information object and the firing of
* events when complete objects are built.
*
* @author Milos Kleint
*/
public class WatchersBuilder implements Builder {
private static final String UNKNOWN_FILE = "? "; //NOI18N
/**
* The status object that is currently being built.
*/
private WatchersInformation watchersInfo;
/**
* The event manager to use.
*/
private final EventManager eventManager;
/**
* The directory where the command was executed.
* Used to compute absolute path to the file.
*/
private final String localPath;
/**
* Creates a WatchersBuilder.
* @param eventManager the event manager that will fire events.
* @param localPath absolute path to the directory where the command was executed.
*/
public WatchersBuilder(EventManager eventManager, String localPath) {
this.eventManager = eventManager;
this.localPath = localPath;
}
public void outputDone() {
if (watchersInfo != null) {
eventManager.fireCVSEvent(new FileInfoEvent(this, watchersInfo));
watchersInfo = null;
}
}
public void parseLine(String line, boolean isErrorMessage) {
if (line.startsWith(UNKNOWN_FILE)) {
File file = new File(localPath, line.substring(UNKNOWN_FILE.length()));
watchersInfo = new WatchersInformation(file);
outputDone();
return;
}
if (isErrorMessage) {
return;
}
if (line.startsWith(" ") || line.startsWith("\t")) { // NOI18N
BugLog.getInstance().assertNotNull(watchersInfo);
watchersInfo.addWatcher(line);
return;
}
// the line starts with file..
outputDone();
String trimmedLine = line.trim().replace('\t', ' ');
int spaceIndex = trimmedLine.indexOf(' ');
BugLog.getInstance().assertTrue(spaceIndex > 0, "Wrong line = " + line);
File file = new File(localPath,
trimmedLine.substring(0, spaceIndex));
String watcher = trimmedLine.substring(spaceIndex + 1);
watchersInfo = new WatchersInformation(file);
watchersInfo.addWatcher(watcher);
}
public void parseEnhancedMessage(String key, Object value) {
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/watchers/WatchersCommand.java 0000644 0001753 0000144 00000014044 11175407000 031215 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.watchers;
import java.io.*;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.request.*;
/**
* The watchers command looks up who is watching this file,
* who is interested in it.
*
* @author Milos Kleint
* @author Thomas Singer
*/
public class WatchersCommand extends BasicCommand {
/**
* Construct a new watchers command.
*/
public WatchersCommand() {
resetCVSCommand();
}
/**
* Creates and returns the WatchersBuilder.
*
* @param eventMan the event manager used to receive events.
*/
public Builder createBuilder(EventManager eventManager) {
return new WatchersBuilder(eventManager, getLocalDirectory());
}
/**
* Executes this command.
*
* @param client the client services object that provides any necessary
* services to this command, including the ability to actually
* process all the requests
*/
public void execute(ClientServices client, EventManager eventManager)
throws CommandException, AuthenticationException {
client.ensureConnection();
super.execute(client, eventManager);
try {
addRequestForWorkingDirectory(client);
addArgumentRequests();
addRequest(CommandRequest.WATCHERS);
client.processRequests(requests);
}
catch (CommandException ex) {
throw ex;
}
catch (Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
finally {
requests.clear();
}
}
/**
* called when server responses with "ok" or "error", (when the command finishes)
*/
public void commandTerminated(TerminationEvent e) {
if (builder != null) {
builder.outputDone();
}
}
/**
* This method returns how the command would looklike when typed on the command line.
* Each command is responsible for constructing this information.
* @returns [] files/dirs. Example: checkout -p CvsCommand.java
*/
public String getCVSCommand() {
StringBuffer toReturn = new StringBuffer("watchers "); //NOI18N
toReturn.append(getCVSArguments());
File[] files = getFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
toReturn.append(files[index].getName());
toReturn.append(' ');
}
}
return toReturn.toString();
}
/**
* takes the arguments and sets the command. To be mainly
* used for automatic settings (like parsing the .cvsrc file)
* @return true if the option (switch) was recognized and set
*/
public boolean setCVSCommand(char opt, String optArg) {
if (opt == 'R') {
setRecursive(true);
}
else if (opt == 'l') {
setRecursive(false);
}
else {
return false;
}
return true;
}
/**
* String returned by this method defines which options are available for this particular command
*/
public String getOptString() {
return "Rl"; //NOI18N
}
/**
* resets all switches in the command. After calling this method,
* the command should have no switches defined and should behave defaultly.
*/
public void resetCVSCommand() {
setRecursive(true);
}
/**
* Returns the arguments of the command in the command-line style.
* Similar to getCVSCommand() however without the files and command's name
*/
public String getCVSArguments() {
StringBuffer toReturn = new StringBuffer();
if (!isRecursive()) {
toReturn.append("-l "); //NOI18N
}
return toReturn.toString();
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/watchers/WatchersInformation.java 0000644 0001753 0000144 00000016376 11175407001 032137 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command.watchers;
import java.io.*;
import java.util.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.util.*;
/**
* Describes "cvs watchers" commands' parsed information for a file.
* The fields in instances of this object are populated
* by response handlers.
*
* @author Milos Kleint
*/
public class WatchersInformation extends FileInfoContainer {
public static final String WATCH_EDIT = "edit"; //NOI18N
public static final String WATCH_UNEDIT = "unedit"; //NOI18N
public static final String WATCH_COMMIT = "commit"; //NOI18N
public static final String WATCH_TEMP_EDIT = "tedit"; //NOI18N
public static final String WATCH_TEMP_UNEDIT = "tunedit"; //NOI18N
public static final String WATCH_TEMP_COMMIT = "tcommit"; //NOI18N
/**
* Holds the file that this info belongs to.
*/
private final File file;
/**
* List of users (Watchers instances) that are listening
* on events for this file.
*/
private final List userList = new LinkedList();
/**
* Creates new istance of the WatchersInformation class.
*/
public WatchersInformation(File file) {
this.file = file;
}
/**
* Getter for file concerned in this instance.
*/
public File getFile() {
return file;
}
/**
* Adds a watcher to the watchers list.
* @param watchingInfo a String that's first word is a user name and the
* rest are watching types.
*/
void addWatcher(String watchingInfo) {
String temp = watchingInfo.trim();
temp = temp.replace('\t', ' ');
int spaceIndex = temp.indexOf(' ');
if (spaceIndex < 0) {
//BUGLOG assert.
}
else {
String user = temp.substring(0, spaceIndex);
String watches = temp.substring(spaceIndex + 1);
this.userList.add(new WatchersInformation.Watcher(user, watches));
}
}
/**
* Returns the Iterator with WatchersInformation.Watcher instances.
* Never returns null.
*/
public Iterator getWatchersIterator() {
return this.userList.iterator();
}
/**
* Inner class that holds information about single user and his watches
* on the file.
*/
public static class Watcher {
private final String userName;
private final String watches;
private boolean watchingEdit;
private boolean watchingUnedit;
private boolean watchingCommit;
private boolean temporaryEdit;
private boolean temporaryUnedit;
private boolean temporaryCommit;
/**
* Package private constuctor that creates a new instance of the Watcher.
* To Be called from outerclass only.
*/
Watcher(String userName, String watches) {
this.userName = userName;
this.watches = watches;
final StringTokenizer tok = new StringTokenizer(watches, " ", false);
while (tok.hasMoreTokens()) {
String token = tok.nextToken();
if (WATCH_EDIT.equals(token)) {
watchingEdit = true;
}
else if (WATCH_UNEDIT.equals(token)) {
watchingUnedit = true;
}
else if (WATCH_COMMIT.equals(token)) {
watchingCommit = true;
}
else if (WATCH_TEMP_COMMIT.equals(token)) {
temporaryCommit = true;
}
else if (WATCH_TEMP_EDIT.equals(token)) {
temporaryEdit = true;
}
else if (WATCH_TEMP_UNEDIT.equals(token)) {
temporaryUnedit = true;
}
else {
BugLog.getInstance().bug("unknown = " + token);
}
}
}
/**
* Gets the user that is watching the file.
*/
public String getUserName() {
return userName;
}
/**
* Returns all the watches defined on the file.
*/
public String getWatches() {
return watches;
}
/**
* User is/isn't watching commit opration.
*/
public boolean isWatchingCommit() {
return watchingCommit;
}
/**
* User is/isn't watching edit opration.
*/
public boolean isWatchingEdit() {
return watchingEdit;
}
/**
* User is/isn't watching unedit opration.
*/
public boolean isWatchingUnedit() {
return watchingUnedit;
}
/**
* User is/isn't temporary watching commit opration.
*/
public boolean isTempWatchingCommit() {
return temporaryCommit;
}
/**
* User is/isn't temporary watching edit opration.
*/
public boolean isTempWatchingEdit() {
return temporaryEdit;
}
/**
* User is/isn't temporary watching unedit opration.
*/
public boolean isTempWatchingUnedit() {
return temporaryUnedit;
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/command/WrapperUtils.java 0000644 0001753 0000144 00000015060 11175416504 026767 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.command;
import org.netbeans.lib.cvsclient.util.SimpleStringPattern;
import org.netbeans.lib.cvsclient.ClientServices;
import java.io.*;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Support for .cvswrappers parsing and merging.
*/
public class WrapperUtils {
/**
* Reads the wrappers from the specified source and populates the specified
* map
*
* @param reader The source of wrappers which is being processed
* @param theMap The map which is being updated
*/
private static void parseWrappers(BufferedReader reader, Map theMap)
throws IOException {
String line;
while ((line = reader.readLine()) != null){
StringTokenizer tokenizer = new StringTokenizer(line);
// the first token is the pattern
SimpleStringPattern pattern = new SimpleStringPattern(tokenizer.nextToken());
// it is followed by option value pairs
String option, value;
while (tokenizer.hasMoreTokens()) {
option = tokenizer.nextToken();
value = tokenizer.nextToken();
// do not bother with the -m Options now
if (option.equals("-k")) { //NOI18N
// This is a keyword substitution option
// strip the quotes
int first = value.indexOf('\'');
int last = value.lastIndexOf('\'');
if (first >=0 && last >= 0) {
value = value.substring(first+1, last);
}
KeywordSubstitutionOptions keywordOption = KeywordSubstitutionOptions.findKeywordSubstOption(value);
if (!theMap.containsKey(pattern)) {
theMap.put(pattern, keywordOption);
}
}
}
}
}
/**
* Reads the wrappers from the specified file and populates the specified
* map
*
* @param file The File object corresponding to the file which is being processed
* @param wrapperMap The map which is being updated
*/
public static void readWrappersFromFile(File file, Map wrapperMap) throws IOException, FileNotFoundException{
parseWrappers(new BufferedReader(new FileReader(file)), wrapperMap);
}
/**
* Reads the wrappers from the specified System property and populates the specified
* map. The map is unchanged if the property is not set.
*
* @param envVar The system variable name
* @param wrapperMap The map which is being updated
*/
private static void readWrappersFromProperty(String envVar, Map wrapperMap) throws IOException {
String propertyValue = System.getenv(envVar);
if (propertyValue != null)
{
parseWrappers(new BufferedReader(new StringReader(propertyValue)), wrapperMap);
}
}
/**
* This method consolidates the wrapper map so that it follows CVS prioritization
* rules for the wrappers. Both AddCommand and ImportCommand will be calling
* this.
*/
public static Map mergeWrapperMap(ClientServices client) throws CommandException
{
String wrapperSource = null;
Map wrappersMap = new java.util.HashMap(client.getWrappersMap());
try
{
File home = new File(System.getProperty("user.home")); // NOI18N
File wrappers = new File(home, "./cvswrappers"); //NOI18N
wrapperSource = CommandException.getLocalMessage("WrapperUtils.clientDotWrapper.text"); //NOI18N
if (wrappers.exists()) {
readWrappersFromFile(wrappers, wrappersMap);
}
wrapperSource = CommandException.getLocalMessage("WrapperUtils.environmentWrapper.text"); //NOI18N
//process the Environment variable CVSWRAPPERS
readWrappersFromProperty("CVSWRAPPERS", wrappersMap); //NOI18N
}
catch (FileNotFoundException fnex) {
// should not happen as we check for file existence. Even if it does
// it just means the .cvswrappers are not there and can be ignored
}
catch (Exception ioex) {
Object [] parms = new Object[1];
parms[0] = wrapperSource;
String localizedMessage = CommandException.getLocalMessage("WrapperUtils.wrapperError.text", parms); //NOI18N
throw new CommandException(ioex, localizedMessage);
}
return wrappersMap;
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/ 0000755 0001753 0000144 00000000000 11175434236 024273 5 ustar ludo users netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/BasicListener.java 0000644 0001753 0000144 00000011142 11175407001 027652 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.commandLine;
import java.io.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.event.*;
/**
* A basic implementation of a CVS listener. Is really only interested in
* message events. This listener is suitable for command line clients and
* clients that don't "persist".
* @author Robert Greig
*/
public class BasicListener extends CVSAdapter {
private final StringBuffer taggedLine = new StringBuffer();
private PrintStream stdout;
private PrintStream stderr;
public BasicListener() {
this(System.out, System.err);
}
public BasicListener(PrintStream stdout, PrintStream stderr) {
this.stdout = stdout;
this.stderr = stderr;
}
/**
* Called when the server wants to send a message to be displayed to
* the user. The message is only for information purposes and clients
* can choose to ignore these messages if they wish.
* @param e the event
*/
public void messageSent(MessageEvent e) {
String line = e.getMessage();
if (e instanceof EnhancedMessageEvent) {
return ;
}
PrintStream stream = e.isError() ? stderr : stdout;
if (e.isTagged()) {
String message = MessageEvent.parseTaggedMessage(taggedLine, e.getMessage());
if (message != null) {
stream.println(message);
}
}
else {
stream.println(line);
}
}
/**
* Called when the server wants to send a binary message to be displayed to
* the user. The message is only for information purposes and clients
* can choose to ignore these messages if they wish.
* @param e the event
*/
public void messageSent(BinaryMessageEvent e) {
byte[] bytes = e.getMessage();
int len = e.getMessageLength();
stdout.write(bytes, 0, len);
}
/**
* Called when file status information has been received
*/
public void fileInfoGenerated(FileInfoEvent e) {
// FileInfoContainer fileInfo = e.getInfoContainer();
// if (fileInfo.getClass().equals(StatusInformation.class)) {
// System.err.println("A file status event was received.");
// System.err.println("The status information object is: " +
// fileInfo);
// }
}
} netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/Bundle.properties 0000644 0001753 0000144 00000006622 11175407001 027616 0 ustar ludo users # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
# Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
#
# The contents of this file are subject to the terms of either the GNU
# General Public License Version 2 only ("GPL") or the Common
# Development and Distribution License("CDDL") (collectively, the
# "License"). You may not use this file except in compliance with the
# License. You can obtain a copy of the License at
# http://www.netbeans.org/cddl-gplv2.html
# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
# specific language governing permissions and limitations under the
# License. When distributing the software, include this License Header
# Notice in each file and include the License file at
# nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the GPL Version 2 section of the License file that
# accompanied this code. If applicable, add the following below the
# License Header, with the fields enclosed by brackets [] replaced by
# your own identifying information:
# "Portions Copyrighted [year] [name of copyright owner]"
#
# Contributor(s):
#
# The Original Software is NetBeans. The Initial Developer of the Original
# Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
# Microsystems, Inc. All Rights Reserved.
#
# If you wish your version of this file to be governed by only the CDDL
# or only the GPL Version 2, indicate your decision by adding
# "[Contributor] elects to include this software in this distribution
# under the [CDDL or GPL Version 2] license." If you do not indicate a
# single choice of license, a recipient has the option to distribute
# your version of this file under either the CDDL, the GPL Version 2 or
# to extend the choice of license to its licensees as provided above.
# However, if you add GPL Version 2 code and therefore, elected the GPL
# Version 2 license, then the option applies only if the new code is
# made subject to such option by the copyright holder.
#--------------------------------------------------------------------
# ResourceBundle properties file
MSG_HelpUsage=Usage: cvs [global options] command [command-options-and-arguments]\n\
\ specify {0} for a list of global options\n\
\ specify {1} for a list of possible commands\n\
\ specify {2} for a list of command synonyms
MSG_HelpOptions=\
CVS global options (specified before the command name) are:\n\
\ -H Displays usage information for command.\n\
\ -q Cause CVS to be somewhat quiet.\n\
\ -Q Cause CVS to be really quiet.\n\
\ -r Make checked-out files read-only.\n\
\ -w Make checked-out files read-write (default).\n\
\ -l Turn history logging off.\n\
\ -n Do not execute anything that will change the disk.\n\
\ -t Show trace of program execution -- try with -n.\n\
\ -v Display JavaCVS version.\n\
\ -T tmpdir Use 'tmpdir' for temporary files.\n\
\ -e editor Use 'editor' for editing log information.\n\
\ -d CVS_root Overrides $CVSROOT as the root of the CVS tree.\n\
\ -f Do not use the ~/.cvsrc file.\n\
\ -z # Use compression level '#' for net traffic.\n\
\ -s VAR=VAL Set CVS user variable.
MSG_CVSCommands=CVS commands are:
MSG_CVSSynonyms=CVS command synonyms are:
MSG_UnknownCommand=Unknown command: ''{0}''
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/CVSCommand.java 0000644 0001753 0000144 00000061030 11175407001 027056 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.commandLine;
import java.io.*;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ResourceBundle;
import org.netbeans.lib.cvsclient.*;
import org.netbeans.lib.cvsclient.CVSRoot;
import org.netbeans.lib.cvsclient.admin.*;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.commandLine.command.CommandProvider;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.lib.cvsclient.connection.StandardScrambler;
import org.netbeans.lib.cvsclient.event.CVSListener;
/**
* An implementation of the standard CVS client utility (command line tool)
* in Java
* @author Robert Greig
*/
public class CVSCommand {
private static final String HELP_OPTIONS = "--help-options"; // NOI18N
private static final String HELP_COMMANDS = "--help-commands"; // NOI18N
private static final String HELP_SYNONYMS = "--help-synonyms"; // NOI18N
/**
* The path to the repository on the server
*/
private String repository;
/**
* The local path to use to perform operations (the top level)
*/
private String localPath;
/**
* The connection to the server
*/
private Connection connection;
/**
* The client that manages interactions with the server
*/
private Client client;
/**
* The global options being used. GlobalOptions are only global for a
* particular command.
*/
private GlobalOptions globalOptions;
/**
* The port number that is used to connect to the remote server.
* It is taken into account only when it's value is greater then zero.
*/
private int port = 0;
/**
* Execute a configured CVS command
* @param command the command to execute
* @throws CommandException if there is an error running the command
*/
public boolean executeCommand(Command command, PrintStream stderr)
throws CommandException, AuthenticationException {
client.setErrorStream(stderr);
return client.executeCommand(command, globalOptions);
}
public void setRepository(String repository) {
this.repository = repository;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
public void setGlobalOptions(GlobalOptions globalOptions) {
this.globalOptions = globalOptions;
}
/**
* Creates the connection and the client and connects.
*/
private void connect(CVSRoot root, String password) throws IllegalArgumentException,
AuthenticationException,
CommandAbortedException {
connection = ConnectionFactory.getConnection(root);
if (CVSRoot.METHOD_PSERVER.equals(root.getMethod())) {
((PServerConnection) connection).setEncodedPassword(password);
if (port > 0) ((PServerConnection) connection).setPort(port);
}
connection.open();
client = new Client(connection, new StandardAdminHandler());
client.setLocalPath(localPath);
}
private void addListener(CVSListener listener) {
if (client != null) {
// add a listener to the client
client.getEventManager().addCVSListener(listener);
}
}
private void close(PrintStream stderr) {
try {
connection.close();
}
catch (IOException e) {
stderr.println("Unable to close connection: " + e);
//e.printStackTrace();
}
}
/**
* Obtain the CVS root, either from the -D option cvs.root or from
* the CVS directory
* @return the CVSRoot string
*/
private static String getCVSRoot(String workingDir) {
String root = null;
BufferedReader r = null;
if (workingDir == null) {
workingDir = System.getProperty("user.dir");
}
try {
File f = new File(workingDir);
File rootFile = new File(f, "CVS/Root");
if (rootFile.exists()) {
r = new BufferedReader(new FileReader(rootFile));
root = r.readLine();
}
}
catch (IOException e) {
// ignore
}
finally {
try {
if (r != null)
r.close();
}
catch (IOException e) {
System.err.println("Warning: could not close CVS/Root file!");
}
}
if (root == null) {
root = System.getProperty("cvs.root");
}
return root;
}
/**
* Process global options passed into the application
* @param args the argument list, complete
* @param globalOptions the global options structure that will be passed
* to the command
*/
private static int processGlobalOptions(String[] args,
GlobalOptions globalOptions,
PrintStream stderr) {
final String getOptString = globalOptions.getOptString();
GetOpt go = new GetOpt(args, getOptString);
int ch = -1;
boolean usagePrint = false;
while ((ch = go.getopt()) != go.optEOF) {
//System.out.println("Global option '"+((char) ch)+"', '"+go.optArgGet()+"'");
boolean success = globalOptions.setCVSCommand((char) ch, go.optArgGet());
if (!success) usagePrint = true;
}
if (usagePrint) {
showUsage(stderr);
return -10;
}
return go.optIndexGet();
}
private static void showUsage(PrintStream stderr) {
String usageStr = ResourceBundle.getBundle(CVSCommand.class.getPackage().getName()+".Bundle").getString("MSG_HelpUsage"); // NOI18N
stderr.println(MessageFormat.format(usageStr, new Object[] { HELP_OPTIONS, HELP_COMMANDS, HELP_SYNONYMS }));
//stderr.println("Usage: cvs [global options] command [command-options-and-arguments]");
//stderr.println(" specify "+HELP_OPTIONS+" for a list of options");
//stderr.println(" specify "+HELP_COMMANDS+" for a list of commands");
//stderr.println(" specify "+HELP_SYNONYMS+" for a list of command synonyms");
}
/**
* Perform the 'login' command, asking the user for a password. If the
* login is successful, the password is written to a file. The file's
* location is user.home, unless the cvs.passfile option is set.
* @param userName the userName
* @param hostName the host
*/
private static boolean performLogin(String userName, String hostName,
String repository, int port,
GlobalOptions globalOptions) {
PServerConnection c = new PServerConnection();
c.setUserName(userName);
String password = null;
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter password: ");
password = in.readLine();
}
catch (IOException e) {
System.err.println("Could not read password: " + e);
return false;
}
String encodedPassword = StandardScrambler.getInstance().scramble(
password);
c.setEncodedPassword(encodedPassword);
c.setHostName(hostName);
c.setRepository(repository);
if (port > 0) c.setPort(port);
try {
c.verify();
}
catch (AuthenticationException e) {
System.err.println("Could not login to host " + hostName);
return false;
}
// was successful, so write the appropriate file out
// we look for cvs.passfile being set, but if not use user.dir
// as the default
String root = globalOptions.getCVSRoot();
try {
PasswordsFile.storePassword(root, encodedPassword);
System.err.println("Logged in successfully to " + repository + " on host " + hostName);
return true;
} catch (IOException e) {
System.err.println("Error: could not write password file.");
return false;
}
}
/**
* Lookup the password in the .cvspass file. This file is looked for
* in the user.home directory if the option cvs.passfile is not set
* @param CVSRoot the CVS root for which the password is being searched
* @return the password, scrambled
*/
private static String lookupPassword(String CVSRoot, String CVSRootWithPort, PrintStream stderr) {
File passFile = new File(System.getProperty("cvs.passfile",
System.getProperty("user.home") +
"/.cvspass"));
BufferedReader reader = null;
String password = null;
try {
reader = new BufferedReader(new FileReader(passFile));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("/1 ")) line = line.substring("/1 ".length());
if (line.startsWith(CVSRoot+" ")) {
password = line.substring(CVSRoot.length() + 1);
break;
} else if (line.startsWith(CVSRootWithPort+" ")) {
password = line.substring(CVSRootWithPort.length() + 1);
break;
}
}
}
catch (IOException e) {
stderr.println("Could not read password for host: " + e);
return null;
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
stderr.println("Warning: could not close password file.");
}
}
}
if (password == null) {
stderr.println("Didn't find password for CVSROOT '"+CVSRoot+"'.");
}
return password;
}
/**
* Execute the CVS command and exit JVM.
*/
public static void main(String[] args) {
if (processCommand(args, null, System.getProperty("user.dir"),
System.out, System.err)) {
System.exit(0);
} else {
System.exit(1);
}
}
/**
* Process the CVS command passed in args[] array with all necessary options.
* The only difference from main() method is, that this method does not exit
* the JVM and provides command output.
* @param args The command with options
* @param files The files to execute the command on.
* @param localPath The local working directory
* @param stdout The standard output of the command
* @param stderr The error output of the command.
*/
public static boolean processCommand(String[] args, File[] files, String localPath,
PrintStream stdout, PrintStream stderr) {
return processCommand(args, files, localPath, 0, stdout, stderr);
}
/**
* Process the CVS command passed in args[] array with all necessary options.
* The only difference from main() method is, that this method does not exit
* the JVM and provides command output.
* @param args The command with options
* @param files The files to execute the command on.
* @param localPath The local working directory
* @param port The port number that is used to connect to the remote server.
* It is taken into account only when it's value is greater then zero.
* @param stdout The standard output of the command
* @param stderr The error output of the command.
* @return whether the command was processed successfully
*/
public static boolean processCommand(String[] args, File[] files, String localPath,
int port, PrintStream stdout, PrintStream stderr) {
assert stdout != null: "The output stream must be defined."; // NOI18N
assert stderr != null: "The error stream must be defined."; // NOI18N
// Provide help if requested
if (args.length > 0) {
if (HELP_OPTIONS.equals(args[0])) {
printHelpOptions(stdout);
return true;
} else if (HELP_COMMANDS.equals(args[0])) {
printHelpCommands(stdout);
return true;
} else if (HELP_SYNONYMS.equals(args[0])) {
printHelpSynonyms(stdout);
return true;
}
}
try { // Adjust the local path
localPath = new File(localPath).getCanonicalPath();
} catch (IOException ioex) {}
// Set up the CVSRoot. Note that it might still be null after this
// call if the user has decided to set it with the -d command line
// global option
GlobalOptions globalOptions = new GlobalOptions();
globalOptions.setCVSRoot(getCVSRoot(localPath));
// Set up any global options specified. These occur before the
// name of the command to run
int commandIndex = -1;
try {
commandIndex = processGlobalOptions(args, globalOptions, stderr);
if (commandIndex == -10) return true;
}
catch (IllegalArgumentException e) {
stderr.println("Invalid argument: " + e);
return false;
}
if (globalOptions.isShowHelp()) {
printHelp(commandIndex, args, stdout, stderr);
return true;
}
if (globalOptions.isShowVersion()) {
printVersion(stdout, stderr);
return true;
}
// if we don't have a CVS root by now, the user has messed up
if (globalOptions.getCVSRoot() == null) {
stderr.println("No CVS root is set. Use the cvs.root " +
"property, e.g. java -Dcvs.root=\":pserver:user@host:/usr/cvs\"" +
" or start the application in a directory containing a CVS subdirectory" +
" or use the -d command switch.");
return false;
}
// parse the CVS root into its constituent parts
CVSRoot root = null;
final String cvsRoot = globalOptions.getCVSRoot();
try {
root = CVSRoot.parse(cvsRoot);
}
catch (IllegalArgumentException e) {
stderr.println("Incorrect format for CVSRoot: " + cvsRoot +
"\nThe correct format is: "+
"[:method:][[user][:password]@][hostname:[port]]/path/to/repository" +
"\nwhere \"method\" is pserver.");
return false;
}
// if we had some options without any command, then the user messed up
if (commandIndex >= args.length) {
showUsage(stderr);
return false;
}
final String command = args[commandIndex];
if (command.equals("login")) {
if (CVSRoot.METHOD_PSERVER.equals(root.getMethod())) {
return performLogin(root.getUserName(), root.getHostName(),
root.getRepository(), root.getPort(),
globalOptions);
}
else {
stderr.println("login does not apply for connection type " +
"\'" + root.getMethod() + "\'");
return false;
}
}
// this is not login, but a 'real' cvs command, so construct it,
// set the options, and then connect to the server and execute it
Command c = null;
try {
c = CommandFactory.getDefault().createCommand(command, args, ++commandIndex, globalOptions, localPath);
}
catch (IllegalArgumentException e) {
stderr.println("Illegal argument: " + e.getMessage());
return false;
}
if (files != null && c instanceof BasicCommand) {
((BasicCommand) c).setFiles(files);
}
String password = null;
if (CVSRoot.METHOD_PSERVER.equals(root.getMethod())) {
password = root.getPassword();
if (password != null) {
password = StandardScrambler.getInstance().scramble(password);
} else {
if (port > 0) root.setPort(port);
password = lookupPassword(cvsRoot, root.toString(), stderr);
if (password == null) {
password = StandardScrambler.getInstance().scramble(""); // an empty password
}
}
}
CVSCommand cvsCommand = new CVSCommand();
cvsCommand.setGlobalOptions(globalOptions);
cvsCommand.setRepository(root.getRepository());
if (port > 0) {
cvsCommand.port = port;
}
// the local path is just the path where we executed the
// command. This is the case for command-line CVS but not
// usually for GUI front-ends
cvsCommand.setLocalPath(localPath);
try {
cvsCommand.connect(root, password);
CVSListener list;
if (c instanceof ListenerProvider)
{
list = ((ListenerProvider)c).createCVSListener(stdout, stderr);
} else {
list = new BasicListener(stdout, stderr);
}
cvsCommand.addListener(list);
boolean status = cvsCommand.executeCommand(c, stderr);
return status;
}
catch (AuthenticationException aex) {
stderr.println(aex.getLocalizedMessage());
return false;
}
catch (CommandAbortedException caex) {
stderr.println("Error: " + caex);
Thread.currentThread().interrupt();
return false;
}
catch (Exception t) {
stderr.println("Error: " + t);
t.printStackTrace(stderr);
return false;
}
finally {
if (cvsCommand != null) {
cvsCommand.close(stderr);
}
}
}
private static void printHelpOptions(PrintStream stdout) {
String options = ResourceBundle.getBundle(CVSCommand.class.getPackage().getName()+".Bundle").getString("MSG_HelpOptions"); // NOI18N
stdout.println(options);
}
private static void printHelpCommands(PrintStream stdout) {
String msg = ResourceBundle.getBundle(CVSCommand.class.getPackage().getName()+".Bundle").getString("MSG_CVSCommands"); // NOI18N
stdout.println(msg);
CommandProvider[] providers = CommandFactory.getDefault().getCommandProviders();
Arrays.sort(providers, new CommandProvidersComparator());
int maxNameLength = 0;
for (int i = 0; i < providers.length; i++) {
int l = providers[i].getName().length();
if (maxNameLength < l) {
maxNameLength = l;
}
}
maxNameLength += 2; // Two spaces from the longest name
for (int i = 0; i < providers.length; i++) {
stdout.print("\t"+providers[i].getName());
char spaces[] = new char[maxNameLength - providers[i].getName().length()];
Arrays.fill(spaces, ' ');
stdout.print(new String(spaces));
providers[i].printShortDescription(stdout);
stdout.println();
}
}
private static void printHelpSynonyms(PrintStream stdout) {
String msg = ResourceBundle.getBundle(CVSCommand.class.getPackage().getName()+".Bundle").getString("MSG_CVSSynonyms"); // NOI18N
stdout.println(msg);
CommandProvider[] providers = CommandFactory.getDefault().getCommandProviders();
Arrays.sort(providers, new CommandProvidersComparator());
int maxNameLength = 0;
for (int i = 0; i < providers.length; i++) {
int l = providers[i].getName().length();
if (maxNameLength < l) {
maxNameLength = l;
}
}
maxNameLength += 2; // Two spaces from the longest name
for (int i = 0; i < providers.length; i++) {
String[] synonyms = providers[i].getSynonyms();
if (synonyms.length > 0) {
stdout.print("\t"+providers[i].getName());
char spaces[] = new char[maxNameLength - providers[i].getName().length()];
Arrays.fill(spaces, ' ');
stdout.print(new String(spaces));
for (int j = 0; j < synonyms.length; j++) {
stdout.print(synonyms[j]+" ");
}
stdout.println();
}
}
}
private static void printHelp(int commandIndex, String[] args,
PrintStream stdout, PrintStream stderr) {
if (commandIndex >= args.length) {
showUsage(stdout);
} else {
String cmdName = args[commandIndex];
CommandProvider provider = CommandFactory.getDefault().getCommandProvider(cmdName);
if (provider == null) {
printUnknownCommand(cmdName, stderr);
} else {
provider.printLongDescription(stdout);
}
}
}
private static void printVersion(PrintStream stdout, PrintStream stderr) {
String version = CVSCommand.class.getPackage().getSpecificationVersion();
stdout.println("Java Concurrent Versions System (JavaCVS) "+version+" (client)");
}
private static void printUnknownCommand(String commandName, PrintStream out) {
String msg = ResourceBundle.getBundle(CVSCommand.class.getPackage().getName()+".Bundle").getString("MSG_UnknownCommand"); // NOI18N
out.println(MessageFormat.format(msg, new Object[] { commandName }));
printHelpCommands(out);
}
private static final class CommandProvidersComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (!(o1 instanceof CommandProvider) || !(o2 instanceof CommandProvider)) {
throw new IllegalArgumentException("Can not compare objects "+o1+" and "+o2);
}
return ((CommandProvider) o1).getName().compareTo(((CommandProvider) o2).getName());
}
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/CommandFactory.java 0000644 0001753 0000144 00000017352 11175407001 030042 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.commandLine;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.commandLine.command.CommandProvider;
/**
* A factory for commands. Given a command name, and any arguments passed to
* that command on the command line, it will return a configured Command
* object, ready for execution.
* @author Robert Greig
* @see org.netbeans.lib.cvsclient.command.Command
*/
public class CommandFactory {
private static final String[] COMMAND_CLASSES = new String[] {
"Import", "add", "annotate", "checkout", "commit", "diff", "export",
"locbundlecheck", "log", "rannotate", "remove", "rlog", "rtag", "status",
"tag", "update" };
private static CommandFactory instance;
private Map commandProvidersByNames;
private CommandFactory() {
createCommandProviders();
}
private void createCommandProviders() {
commandProvidersByNames = new HashMap();
String packageName = CommandFactory.class.getPackage().getName() + ".command.";
for (int i = 0; i < COMMAND_CLASSES.length; i++) {
Class providerClass;
try {
providerClass = Class.forName(packageName + COMMAND_CLASSES[i]);
CommandProvider provider = (CommandProvider) providerClass.newInstance();
commandProvidersByNames.put(provider.getName(), provider);
String[] synonyms = provider.getSynonyms();
for (int j = 0; j < synonyms.length; j++) {
commandProvidersByNames.put(synonyms[j], provider);
}
} catch (Exception e) {
System.err.println("Creation of command '"+COMMAND_CLASSES[i]+"' failed:");
e.printStackTrace(System.err);
continue;
}
}
}
/**
* Get the default instance of CommandFactory.
*/
public static synchronized CommandFactory getDefault() {
if (instance == null) {
instance = new CommandFactory();
}
return instance;
}
/**
* Create a CVS command.
* @param commandName The name of the command to create
* @param args The array of arguments
* @param startingIndex The index of the first argument of the command in the array
* @param workingDir The working directory
*/
public Command createCommand(String commandName, String[] args,
int startingIndex, GlobalOptions gopt,
String workingDir) throws IllegalArgumentException {
CommandProvider provider = (CommandProvider) commandProvidersByNames.get(commandName);
if (provider == null) {
throw new IllegalArgumentException("Unknown command: '"+commandName+"'");
}
return provider.createCommand(args, startingIndex, gopt, workingDir);
}
/**
* Get the provider of a command.
* @param name The name of the command to get the provider for.
*/
public CommandProvider getCommandProvider(String name) {
return (CommandProvider) commandProvidersByNames.get(name);
}
/**
* Get the array of all command providers.
*/
public CommandProvider[] getCommandProviders() {
Set providers = new HashSet(commandProvidersByNames.values());
return (CommandProvider[]) providers.toArray(new CommandProvider[0]);
}
/*
public static Command getCommand(String commandName, String[] args,
int startingIndex, String workingDir)
throws IllegalArgumentException {
Class helper;
try {
helper = Class.forName("org.netbeans.lib.cvsclient.commandLine." +
"command." + commandName);
}
catch (Exception e) {
commandName = Character.toUpperCase(commandName.charAt(0)) + commandName.substring(1);
try {
helper = Class.forName("org.netbeans.lib.cvsclient.commandLine." +
"command." + commandName);
}
catch (Exception ex) {
System.err.println("Exception is: " + ex);
throw new IllegalArgumentException("Unknown command " +
commandName);
}
}
// the method invoked can throw an exception
try {
Method m = helper.getMethod("createCommand", new Class[]{
String[].class,
Integer.class,
String.class});
return (Command) m.invoke(null, new Object[] { args,
new Integer(startingIndex), workingDir });
}
catch (IllegalArgumentException e) {
throw e;
}
catch (InvocationTargetException ite) {
Throwable t = ite.getCause();
if (t instanceof IllegalArgumentException) {
throw (IllegalArgumentException) t;
} else {
IllegalArgumentException iaex = new IllegalArgumentException(t.getMessage());
iaex.initCause(t);
throw iaex;
}
}
catch (Exception e) {
IllegalArgumentException iaex = new IllegalArgumentException(e.getMessage());
iaex.initCause(e);
throw iaex;
}
}
*/
} netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/GetOpt.java 0000644 0001753 0000144 00000040045 11175407001 026331 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Robert Greig.
* Portions created by Robert Greig are Copyright (C) 2000.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
* Contributor(s): Robert Greig.
*****************************************************************************/
package org.netbeans.lib.cvsclient.commandLine;
/**
* Overview
*
* GetOpt provides a general means for a Java program to parse command
* line arguments in accordance with the standard Unix conventions;
* it is analogous to, and based on, getopt(3) for C programs.
* (The following documentation is based on the man page for getopt(3).)
* Description
*
* GetOpt is a Java class that provides one method, getopt,
* and some variables that control behavior of or return additional
* information from getopt.
*
* GetOpt interprets command arguments in accordance with the standard
* Unix conventions: option arguments of a command are introduced by "-"
* followed by a key character, and a non-option argument terminates
* the processing of options. GetOpt's option interpretation is controlled
* by its parameter optString, which specifies what characters designate
* legal options and which of them require associated values.
*
* The getopt method returns the next, moving left to right, option letter
* in the command line arguments that matches a letter in optString.
* optString must contain the option letters the command using getopt
* will recognize. For example, getopt("ab") specifies that the command
* line should contain no options, only "-a", only "-b", or both "-a" and
* "-b" in either order. (The command line can also contain non-option
* arguments after any option arguments.) Multiple options per argument
* are allowed, e.g., "-ab" for the last case above.
*
* If a letter in optString is followed by a colon, the option is expected
* to have an argument. The argument may or may not be separated by
* whitespace from the option letter. For example, getopt("w:") allows
* either "-w 80" or "-w80". The variable optArg is set to the option
* argument, e.g., "80" in either of the previous examples. Conversion
* functions such as Integer.parseInt(), etc., can then be applied to
* optArg.
*
* getopt places in the variable optIndex the index of the next command
* line argument to be processed; optIndex is automatically initialized
* to 1 before the first call to getopt.
*
* When all options have been processed (that is, up to the first
* non-option argument), getopt returns optEOF (-1). getopt recognizes the
* command line argument "--" (i.e., two dashes) to delimit the end of
* the options; getopt returns optEOF and skips "--". Subsequent,
* non-option arguments can be retrieved using the String array passed to
* main(), beginning with argument number optIndex.
*
*
Diagnostics
*
* getopt prints an error message on System.stderr and returns a question
* mark ('?') when it encounters an option letter in a command line argument
* that is not included in optString. Setting the variable optErr to
* false disables this error message.
* Notes
*
* The following notes describe GetOpt's behavior in a few interesting
* or special cases; these behaviors are consistent with getopt(3)'s
* behaviors.
* -- A '-' by itself is treated as a non-option argument.
* -- If optString is "a:" and the command line arguments are "-a -x",
* then "-x" is treated as the argument associated with the "-a".
* -- Duplicate command line options are allowed; it is up to user to
* deal with them as appropriate.
* -- A command line option like "-b-" is considered as the two options
* "b" and "-" (so "-" should appear in option string); this differs
* from "-b --".
* -- Sun and DEC getopt(3)'s differ w.r.t. how "---" is handled.
* Sun treats "---" (or anything starting with "--") the same as "--"
* DEC treats "---" as two separate "-" options
* (so "-" should appear in option string).
* Java GetOpt follows the DEC convention.
* -- An option `letter' can be a letter, number, or most special character.
* Like getopt(3), GetOpt disallows a colon as an option letter.
*
* @author Anonymous
*****************************************************************************/
public class GetOpt {
private String[] theArgs = null;
private int argCount = 0;
private String optString = null;
public GetOpt(String[] args, String opts) {
theArgs = args;
argCount = theArgs.length;
optString = opts;
}
// user can toggle this to control printing of error messages
public boolean optErr = false;
public int processArg(String arg, int n) {
int value;
try {
value = Integer.parseInt(arg);
}
catch (NumberFormatException e) {
if (optErr)
System.err.println("processArg cannot process " + arg //NOI18N
+ " as an integer"); //NOI18N
return n;
}
return value;
}
public int tryArg(int k, int n) {
int value;
try {
value = processArg(theArgs[k], n);
}
catch (ArrayIndexOutOfBoundsException e) {
if (optErr)
System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
return n;
}
return value;
}
public long processArg(String arg, long n) {
long value;
try {
value = Long.parseLong(arg);
}
catch (NumberFormatException e) {
if (optErr)
System.err.println("processArg cannot process " + arg //NOI18N
+ " as a long"); //NOI18N
return n;
}
return value;
}
public long tryArg(int k, long n) {
long value;
try {
value = processArg(theArgs[k], n);
}
catch (ArrayIndexOutOfBoundsException e) {
if (optErr)
System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
return n;
}
return value;
}
public double processArg(String arg, double d) {
double value;
try {
value = Double.valueOf(arg).doubleValue();
}
catch (NumberFormatException e) {
if (optErr)
System.err.println("processArg cannot process " + arg //NOI18N
+ " as a double"); //NOI18N
return d;
}
return value;
}
public double tryArg(int k, double d) {
double value;
try {
value = processArg(theArgs[k], d);
}
catch (ArrayIndexOutOfBoundsException e) {
if (optErr)
System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
return d;
}
return value;
}
public float processArg(String arg, float f) {
float value;
try {
value = Float.valueOf(arg).floatValue();
}
catch (NumberFormatException e) {
if (optErr)
System.err.println("processArg cannot process " + arg //NOI18N
+ " as a float"); //NOI18N
return f;
}
return value;
}
public float tryArg(int k, float f) {
float value;
try {
value = processArg(theArgs[k], f);
}
catch (ArrayIndexOutOfBoundsException e) {
if (optErr)
System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
return f;
}
return value;
}
public boolean processArg(String arg, boolean b) {
// `true' in any case mixture is true; anything else is false
return Boolean.valueOf(arg).booleanValue();
}
public boolean tryArg(int k, boolean b) {
boolean value;
try {
value = processArg(theArgs[k], b);
}
catch (ArrayIndexOutOfBoundsException e) {
if (optErr)
System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
return b;
}
return value;
}
public String tryArg(int k, String s) {
String value;
try {
value = theArgs[k];
}
catch (ArrayIndexOutOfBoundsException e) {
if (optErr)
System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
return s;
}
return value;
}
private static void writeError(String msg, char ch) {
System.err.println("GetOpt: " + msg + " -- " + ch); //NOI18N
}
public static final int optEOF = -1;
private int optIndex = 0;
public int optIndexGet() {
return optIndex;
}
public void optIndexSet(int i) {
optIndex = i;
}
private String optArg = null;
public String optArgGet() {
return optArg;
}
private int optPosition = 1;
public int getopt() {
optArg = null;
if (theArgs == null || optString == null)
return optEOF;
if (optIndex < 0 || optIndex >= argCount)
return optEOF;
String thisArg = theArgs[optIndex];
int argLength = thisArg.length();
// handle special cases
if (argLength <= 1 || thisArg.charAt(0) != '-') {
// e.g., "", "a", "abc", or just "-"
return optEOF;
}
else if (thisArg.equals("--")) {//NOI18N
// end of non-option args
optIndex++;
return optEOF;
}
// get next "letter" from option argument
char ch = thisArg.charAt(optPosition);
// find this option in optString
int pos = optString.indexOf(ch);
if (pos == -1 || ch == ':') {
if (optErr) {
writeError("illegal option", ch); //NOI18N
}
ch = '?';
}
else { // handle colon, if present
if (pos < optString.length() - 1 && optString.charAt(pos + 1) == ':') {
if (optPosition != argLength - 1) {
// take rest of current arg as optArg
optArg = thisArg.substring(optPosition + 1);
optPosition = argLength - 1; // force advance to next arg below
}
else { // take next arg as optArg
optIndex++;
if (optIndex < argCount
&& (theArgs[optIndex].charAt(0) != '-' ||
theArgs[optIndex].length() >= 2 &&
(optString.indexOf(theArgs[optIndex].charAt(1)) == -1
|| theArgs[optIndex].charAt(1) == ':'))) {
optArg = theArgs[optIndex];
}
else {
if (optErr) {
writeError("option requires an argument", ch); //NOI18N
}
optArg = null;
ch = ':'; // Linux man page for getopt(3) says : not ?
}
}
}
}
// advance to next option argument,
// which might be in thisArg or next arg
optPosition++;
if (optPosition >= argLength) {
optIndex++;
optPosition = 1;
}
return ch;
}
public static void main(String[] args) { // test the class
GetOpt go = new GetOpt(args, "Uab:f:h:w:");
go.optErr = true;
int ch = -1;
// process options in command line arguments
boolean usagePrint = false; // set
int aflg = 0; // default
boolean bflg = false; // values
String filename = "out"; // of
int width = 80; // options
double height = 1; // here
while ((ch = go.getopt()) != go.optEOF) {
if ((char)ch == 'U')
usagePrint = true;
else if ((char)ch == 'a')
aflg++;
else if ((char)ch == 'b')
bflg = go.processArg(go.optArgGet(), bflg);
else if ((char)ch == 'f')
filename = go.optArgGet();
else if ((char)ch == 'h')
height = go.processArg(go.optArgGet(), height);
else if ((char)ch == 'w')
width = go.processArg(go.optArgGet(), width);
else
System.exit(1); // undefined option
} // getopt() returns '?'
if (usagePrint) {
System.out.println("Usage: -a -b bool -f file -h height -w width"); //NOI18N
System.exit(0);
}
System.out.println("These are all the command line arguments " + //NOI18N
"before processing with GetOpt:"); //NOI18N
for (int i = 0; i < args.length; i++) {
System.out.print(" " + args[i]); //NOI18N
}
System.out.println();
System.out.println("-U " + usagePrint); //NOI18N
System.out.println("-a " + aflg); //NOI18N
System.out.println("-b " + bflg); //NOI18N
System.out.println("-f " + filename); //NOI18N
System.out.println("-h " + height); //NOI18N
System.out.println("-w " + width); //NOI18N
// process non-option command line arguments
for (int k = go.optIndexGet(); k < args.length; k++) {
System.out.println("normal argument " + k + " is " + args[k]); //NOI18N
}
}
}
/* ............... Example compile and run(s)
D:\>javac GetOpt.java
D:\>java GetOpt -aaa -b true -f theFile -w -80 -h3.33 arg1 arg2
These are all the command line arguments before processing with GetOpt:
-aaa -b true -f theFile -w -80 -h3.33 arg1 arg2
-U false
-a 3
-b true
-f theFile
-h 3.33
-w -80
normal argument 8 is arg1
normal argument 9 is arg2
D:\>java GetOpt -aaa -x -w90
GetOpt: illegal option -- x
D:\>java GetOpt -af theFile -w -b true
GetOpt: option requires an argument -- w
... end of example run(s) */
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/ListenerProvider.java 0000644 0001753 0000144 00000005272 11175407001 030432 0 ustar ludo users /*****************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is the CVS Client Library.
* The Initial Developer of the Original Software is Milos Kleint.
* Portions created by Milos Kleint are Copyright (C) 2003.
* All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
* Contributor(s): Milos Kleint.
*****************************************************************************/
package org.netbeans.lib.cvsclient.commandLine;
import java.io.PrintStream;
import org.netbeans.lib.cvsclient.event.CVSListener;
/**
* for commands created in commandLine.command, that don't want to have the BasicListener
* attached to the created command, but rather a custom one.
* @author milos
*/
public interface ListenerProvider
{
/**
*
*/
CVSListener createCVSListener(PrintStream stdout, PrintStream stderr);
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/command/ 0000755 0001753 0000144 00000000000 11175434236 025711 5 ustar ludo users ././@LongLink 0000000 0000000 0000000 00000000147 00000000000 011567 L ustar root root netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/command/AbstractCommandProvider.java netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/command/AbstractCommandProvider.ja0000644 0001753 0000144 00000007133 11175407001 032774 0 ustar ludo users /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.cvsclient.commandLine.command;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import org.netbeans.lib.cvsclient.command.Command;
/**
* The provider of CVS commands.
* The implementation of this interface knows how to create a CVS command
* from an array of arguments.
*
* @author Martin Entlicher
*/
abstract class AbstractCommandProvider implements CommandProvider {
/**
* Get the name of this command.
* The default implementation returns the name of the implementing class.
*/
public String getName() {
String className = getClass().getName();
int dot = className.lastIndexOf('.');
if (dot > 0) {
return className.substring(dot + 1);
} else {
return className;
}
}
public String getUsage() {
return ResourceBundle.getBundle(CommandProvider.class.getPackage().getName()+".Bundle").getString(getName()+".usage"); // NOI18N
}
public void printShortDescription(PrintStream out) {
String msg = ResourceBundle.getBundle(CommandProvider.class.getPackage().getName()+".Bundle").getString(getName()+".shortDescription"); // NOI18N
out.print(msg);
}
public void printLongDescription(PrintStream out) {
String msg = ResourceBundle.getBundle(CommandProvider.class.getPackage().getName()+".Bundle").getString(getName()+".longDescription"); // NOI18N
out.println(MessageFormat.format(msg, new Object[] { getUsage() }));
}
}
netbeans-cvsclient_6.5/src/org/netbeans/lib/cvsclient/commandLine/command/Bundle.properties 0000644 0001753 0000144 00000031267 11175407001 031237 0 ustar ludo users # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
# Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
#
# The contents of this file are subject to the terms of either the GNU
# General Public License Version 2 only ("GPL") or the Common
# Development and Distribution License("CDDL") (collectively, the
# "License"). You may not use this file except in compliance with the
# License. You can obtain a copy of the License at
# http://www.netbeans.org/cddl-gplv2.html
# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
# specific language governing permissions and limitations under the
# License. When distributing the software, include this License Header
# Notice in each file and include the License file at
# nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the GPL Version 2 section of the License file that
# accompanied this code. If applicable, add the following below the
# License Header, with the fields enclosed by brackets [] replaced by
# your own identifying information:
# "Portions Copyrighted [year] [name of copyright owner]"
#
# Contributor(s):
#
# The Original Software is NetBeans. The Initial Developer of the Original
# Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
# Microsystems, Inc. All Rights Reserved.
#
# If you wish your version of this file to be governed by only the CDDL
# or only the GPL Version 2, indicate your decision by adding
# "[Contributor] elects to include this software in this distribution
# under the [CDDL or GPL Version 2] license." If you do not indicate a
# single choice of license, a recipient has the option to distribute
# your version of this file under either the CDDL, the GPL Version 2 or
# to extend the choice of license to its licensees as provided above.
# However, if you add GPL Version 2 code and therefore, elected the GPL
# Version 2 license, then the option applies only if the new code is
# made subject to such option by the copyright holder.
#--------------------------------------------------------------------
# ResourceBundle properties file
add.usage=add [-k rcs-kflag] [-m message] files...
add.shortDescription=Add a new file/directory to the repository.
add.longDescription=Usage: {0}\n\
\ -k Use "rcs-kflag" to add the file with the specified kflag.\n\
\ -m Use "message" for the creation log.
annotate.usage=annotate [-lRf] [-r rev|-D date] [files...]
annotate.shortDescription=Show the last revision where each source line was modified.
annotate.longDescription=Usage: {0}\n\
\ -l Local directory only, no recursion.\
\ -R Process directories recursively.\
\ -f Use head revision if tag/date not found.\
\ -r rev Annotate file as of specified revision/tag.\
\ -D date Annotate file as of specified date.
checkout.usage=checkout [-ANPRcflnps] [-r rev | -D date] [-d dir] [-j rev1] [-j rev2] [-k kopt] modules...
checkout.shortDescription=Check out the sources from repository to local working directory.
checkout.longDescription=Usage: {0}\n\
\ -A Reset any sticky tags/date/kopts.\n\
\ -N Don't shorten module paths if -d specified.\n\
\ -P Prune empty directories.\n\
\ -R Process directories recursively.\n\
\ -c "cat" the module database.\n\
\ -f Force a head revision match if tag/date not found.\n\
\ -l Local directory only, not recursive\n\
\ -n Do not run module program (if any).\n\
\ -p Check out files to standard output (avoids stickiness).\n\
\ -s Like -c, but include module status.\n\
\ -r rev Check out revision or tag. (implies -P) (is sticky)\n\
\ -D date Check out revisions as of date. (implies -P) (is sticky)\n\
\ -d dir Check out into dir instead of module name.\n\
\ -k kopt Use RCS kopt -k option on checkout.\n\
\ -j rev Merge in changes made between current revision and rev.
commit.usage=commit [-nRlf] [-m msg | -F logfile] [-r rev] files...
commit.shortDescription=Check files into the repository.
commit.longDescription=Usage: {0}\n\
\ -n Do not run the module program (if any).\n\
\ -R Process directories recursively.\n\
\ -l Local directory only (not recursive).\n\
\ -f Force the file to be committed; disables recursion.\n\
\ -F file Read the log message from file.\n\
\ -m msg Log message.\n\
\ -r rev Commit to this branch or trunk revision.
commit.messageNotSpecified=The message was not specified. Please use -m or -F options.
diff.usage=diff [-lNR] [rcsdiff-options] [[-r rev1 | -D date1] [-r rev2 | -D date2]] [files...]
diff.shortDescription=Show differences between local file and a revision, or between two revisions.
diff.longDescription=Usage: {0}\n\
\ -l Local directory only, not recursive\n\
\ -R Process directories recursively.\n\
\ -D d1 Diff revision for date against working file.\n\
\ -D d2 Diff rev1/date1 against date2.\n\
\ -N include diffs for added and removed files.\n\
\ -r rev1 Diff revision for rev1 against working file.\n\
\ -r rev2 Diff rev1/date1 against rev2.\n\
\ --ifdef=arg Output diffs in ifdef format.\n\
(consult the documentation for the CVS server diff program for rcsdiff-options.\n\
The most popular is -c for context diffs but there are many more).
export.usage=export [-NPRfln] [-r rev | -D date] [-d dir] [-k kopt] module...
export.shortDescription=Export sources from CVS, without administrative files.
export.longDescription=Usage: {0}\n\
\ -N Don't shorten module paths if -d specified.\n\
\ -f Force a head revision match if tag/date not found.\n\
\ -l Local directory only, not recursive.\n\
\ -R Process directories recursively (default).\n\
\ -P Prune empty directories.\n\
\ -n Do not run module program (if any).\n\
\ -r rev Export revision or tag.\n\
\ -D date Export revisions as of date.\n\
\ -d dir Export into dir instead of module name.\n\
\ -k kopt Use RCS kopt -k option on checkout.\n
export.Msg_NeedTagOrDate=must specify a tag or date
import.usage=import [-d] [-k subst] [-I ign] [-m msg] [-b branch] [-W spec] repository vendor-tag release-tags...
import.shortDescription=Import sources into CVS repository, using a vendor branch.
import.longDescription=Usage: {0}\n\
\ -d Use the file's modification time as the time of import.\n\
\ -k sub Set default RCS keyword substitution mode.\n\
\ -I ign More files to ignore (! to reset).\n\
\ -b bra Vendor branch id.\n\
\ -m msg Log message.\n\
\ -W spec Wrappers specification line.
locbundlecheck.usage=locbundlecheck -i [] [files...]
locbundlecheck.shortDescription=Detect what bundle keys need to be updated in localized resource bundles.
locbundlecheck.longDescription=Usage: {0}\n\
\ -i locale The locale to check\n\
(all switches that can be applied to annotate can be specified here as well).
locbundlecheck.no_file_spec=no files specified
locbundlecheck.illegal_state=illegal state
locbundlecheck.noLocalizedFile=File {0} doesn't have a localized counterpart.
locbundlecheck.File=File {0}
locbundlecheck.propMissing=\ \ \ Property \"{0}\" doesn't exist in localized file.
locbundlecheck.prop_updated=\ \ \ Property \"{0}\" was updated in the original file.
locbundlecheck.prop_removed=\ \ \ Property \"{0}\" was removed from original file.
log.usage=log [-lRbhtN] [-d ] [-r ] [-s ] [-w[logins]] [files...]
log.shortDescription=Print out history information for files
log.longDescription=Usage: {0}\n\
\ -l Local directory only, no recursion.\n\
\ -R Only print name of RCS file.\n\
\ -h Only print header.\n\
\ -t Only print header and descriptive text.\n\
\ -N Do not list tags.\n\
\ -b Only list revisions on the default branch.\n\
\ -r[revisions] Specify revision(s)s to list.\n\
\ -d dates Specify dates (D1] [-r ] [-s ] [-w[logins]] files...
rlog.shortDescription=Print out history information for files
rlog.longDescription=Usage: {0}\n\
Like log, but acts directly on files in repository, does not operate on check out sources.\
\ -l Local directory only, no recursion.\n\
\ -R Only print name of RCS file.\n\
\ -h Only print header.\n\
\ -t Only print header and descriptive text.\n\
\ -N Do not list tags.\n\
\ -b Only list revisions on the default branch.\n\
\ -r[revisions] Specify revision(s)s to list.\n\
\ -d dates Specify dates (D1