diff src/org/tmatesoft/hg/repo/HgLookup.java @ 181:cd3371670f0b

Refactor incoming and outgoing code to be shared with RepositoryComparator. Placeholders for in/out commands. Refactor common remote lookup code
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Tue, 12 Apr 2011 19:10:38 +0200
parents 87f40938c9b2
children 44a34baabea0
line wrap: on
line diff
--- a/src/org/tmatesoft/hg/repo/HgLookup.java	Wed Apr 06 03:08:05 2011 +0200
+++ b/src/org/tmatesoft/hg/repo/HgLookup.java	Tue Apr 12 19:10:38 2011 +0200
@@ -18,10 +18,14 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.net.MalformedURLException;
 import java.net.URL;
 
+import org.tmatesoft.hg.core.HgBadArgumentException;
 import org.tmatesoft.hg.core.HgException;
+import org.tmatesoft.hg.internal.ConfigFile;
 import org.tmatesoft.hg.internal.DataAccessProvider;
+import org.tmatesoft.hg.internal.Internals;
 
 /**
  * Utility methods to find Mercurial repository at a given location
@@ -31,6 +35,8 @@
  */
 public class HgLookup {
 
+	private ConfigFile globalCfg;
+
 	public HgRepository detectFromWorkingDir() throws HgException {
 		return detect(System.getProperty("user.dir"));
 	}
@@ -70,7 +76,38 @@
 		}
 		return new HgBundle(new DataAccessProvider(), location);
 	}
-
+	
+	/**
+	 * Try to instantiate remote server.
+	 * @param key either URL or a key from configuration file that points to remote server  
+	 * @param hgRepo <em>NOT USED YET<em> local repository that may have extra config, or default remote location
+	 * @return an instance featuring access to remote repository, check {@link HgRemoteRepository#isInvalid()} before actually using it
+	 * @throws HgBadArgumentException if anything is wrong with the remote server's URL
+	 */
+	public HgRemoteRepository detectRemote(String key, HgRepository hgRepo) throws HgBadArgumentException {
+		URL url;
+		Exception toReport;
+		try {
+			url = new URL(key);
+			toReport = null;
+		} catch (MalformedURLException ex) {
+			url = null;
+			toReport = ex;
+		}
+		if (url == null) {
+			String server = getGlobalConfig().getSection("paths").get(key);
+			if (server == null) {
+				throw new HgBadArgumentException(String.format("Can't find server %s specification in the config", key), toReport);
+			}
+			try {
+				url = new URL(server);
+			} catch (MalformedURLException ex) {
+				throw new HgBadArgumentException(String.format("Found %s server spec in the config, but failed to initialize with it", key), ex);
+			}
+		}
+		return new HgRemoteRepository(url);
+	}
+	
 	public HgRemoteRepository detect(URL url) throws HgException {
 		if (url == null) {
 			throw new IllegalArgumentException();
@@ -80,4 +117,12 @@
 		}
 		return new HgRemoteRepository(url);
 	}
+
+	private ConfigFile getGlobalConfig() {
+		if (globalCfg == null) {
+			globalCfg = new Internals().newConfigFile();
+			globalCfg.addLocation(new File(System.getProperty("user.home"), ".hgrc"));
+		}
+		return globalCfg;
+	}
 }