--- /dev/null
+/*\r
+ * \r
+ * Copyright 2001-2004 The Ant-Contrib project\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+package net.sf.antcontrib.cpptasks;\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.Enumeration;\r
+import java.util.Hashtable;\r
+import java.util.StringTokenizer;\r
+import java.util.Vector;\r
+\r
+import org.apache.tools.ant.BuildException;\r
+import org.apache.tools.ant.Project;\r
+import org.apache.tools.ant.taskdefs.Execute;\r
+import org.apache.tools.ant.taskdefs.LogStreamHandler;\r
+import org.apache.tools.ant.types.Commandline;\r
+import org.apache.tools.ant.types.Environment;\r
+/**\r
+ * Some utilities used by the CC and Link tasks.\r
+ * \r
+ * @author Adam Murdoch\r
+ */\r
+public class CUtil {\r
+ /**\r
+ * A class that splits a white-space, comma-separated list into a String\r
+ * array. Used for task attributes.\r
+ */\r
+ public static final class StringArrayBuilder {\r
+ private String[] _value;\r
+ public StringArrayBuilder(String value) {\r
+ // Split the defines up\r
+ StringTokenizer tokens = new StringTokenizer(value, ", ");\r
+ Vector vallist = new Vector();\r
+ while (tokens.hasMoreTokens()) {\r
+ String val = tokens.nextToken().trim();\r
+ if (val.length() == 0) {\r
+ continue;\r
+ }\r
+ vallist.addElement(val);\r
+ }\r
+ _value = new String[vallist.size()];\r
+ vallist.copyInto(_value);\r
+ }\r
+ public String[] getValue() {\r
+ return _value;\r
+ }\r
+ }\r
+ /**\r
+ * Adds the elements of the array to the given vector\r
+ */\r
+ public static void addAll(Vector dest, Object[] src) {\r
+ if (src == null) {\r
+ return;\r
+ }\r
+ for (int i = 0; i < src.length; i++) {\r
+ dest.addElement(src[i]);\r
+ }\r
+ }\r
+ /**\r
+ * Checks a array of names for non existent or non directory entries and\r
+ * nulls them out.\r
+ * \r
+ * @return Count of non-null elements\r
+ */\r
+ public static int checkDirectoryArray(String[] names) {\r
+ int count = 0;\r
+ for (int i = 0; i < names.length; i++) {\r
+ if (names[i] != null) {\r
+ File dir = new File(names[i]);\r
+ if (dir.exists() && dir.isDirectory()) {\r
+ count++;\r
+ } else {\r
+ names[i] = null;\r
+ }\r
+ }\r
+ }\r
+ return count;\r
+ }\r
+ /**\r
+ * Extracts the basename of a file, removing the extension, if present\r
+ */\r
+ public static String getBasename(File file) {\r
+ String path = file.getPath();\r
+ // Remove the extension\r
+ String basename = file.getName();\r
+ int pos = basename.lastIndexOf('.');\r
+ if (pos != -1) {\r
+ basename = basename.substring(0, pos);\r
+ }\r
+ return basename;\r
+ }\r
+ /**\r
+ * Gets the parent directory for the executable file name using the current\r
+ * directory and system executable path\r
+ * \r
+ * @param exeName\r
+ * Name of executable such as "cl.exe"\r
+ * @return parent directory or null if not located\r
+ */\r
+ public static File getExecutableLocation(String exeName) {\r
+ //\r
+ // must add current working directory to the\r
+ // from of the path from the "path" environment variable\r
+ File currentDir = new File(System.getProperty("user.dir"));\r
+ if (new File(currentDir, exeName).exists()) {\r
+ return currentDir;\r
+ }\r
+ File[] envPath = CUtil.getPathFromEnvironment("PATH",\r
+ File.pathSeparator);\r
+ for (int i = 0; i < envPath.length; i++) {\r
+ if (new File(envPath[i], exeName).exists()) {\r
+ return envPath[i];\r
+ }\r
+ }\r
+ return null;\r
+ }\r
+ /**\r
+ * Extracts the parent of a file\r
+ */\r
+ public static String getParentPath(String path) {\r
+ int pos = path.lastIndexOf(File.separator);\r
+ if (pos <= 0) {\r
+ return null;\r
+ }\r
+ return path.substring(0, pos);\r
+ }\r
+ /**\r
+ * Returns an array of File for each existing directory in the specified\r
+ * environment variable\r
+ * \r
+ * @param envVariable\r
+ * environment variable name such as "LIB" or "INCLUDE"\r
+ * @param delim\r
+ * delimitor used to separate parts of the path, typically ";"\r
+ * or ":"\r
+ * @return array of File's for each part that is an existing directory\r
+ */\r
+ public static File[] getPathFromEnvironment(String envVariable, String delim) {\r
+ // OS/4000 does not support the env command.\r
+ if (System.getProperty("os.name").equals("OS/400"))\r
+ return new File[]{};\r
+ Vector osEnv = Execute.getProcEnvironment();\r
+ String match = envVariable.concat("=");\r
+ for (Enumeration e = osEnv.elements(); e.hasMoreElements();) {\r
+ String entry = ((String) e.nextElement()).trim();\r
+ if (entry.length() > match.length()) {\r
+ String entryFrag = entry.substring(0, match.length());\r
+ if (entryFrag.equalsIgnoreCase(match)) {\r
+ String path = entry.substring(match.length());\r
+ return parsePath(path, delim);\r
+ }\r
+ }\r
+ }\r
+ File[] noPath = new File[0];\r
+ return noPath;\r
+ }\r
+ /**\r
+ * Returns a relative path for the targetFile relative to the base\r
+ * directory.\r
+ * \r
+ * @param canonicalBase\r
+ * base directory as returned by File.getCanonicalPath()\r
+ * @param targetFile\r
+ * target file\r
+ * @return relative path of target file. Returns targetFile if there were\r
+ * no commonalities between the base and the target\r
+ * \r
+ * @author Curt Arnold\r
+ */\r
+ public static String getRelativePath(String base, File targetFile) {\r
+ try {\r
+ //\r
+ // remove trailing file separator\r
+ //\r
+ String canonicalBase = base;\r
+ if (base.charAt(base.length() - 1) == File.separatorChar) {\r
+ canonicalBase = base.substring(0, base.length() - 1);\r
+ }\r
+ //\r
+ // get canonical name of target and remove trailing separator\r
+ //\r
+ String canonicalTarget;\r
+ if (System.getProperty("os.name").equals("OS/400"))\r
+ canonicalTarget = targetFile.getPath();\r
+ else\r
+ canonicalTarget = targetFile.getCanonicalPath();\r
+ if (canonicalTarget.charAt(canonicalTarget.length() - 1) == File.separatorChar) {\r
+ canonicalTarget = canonicalTarget.substring(0, canonicalTarget\r
+ .length() - 1);\r
+ }\r
+ if (canonicalTarget.equals(canonicalBase)) {\r
+ return ".";\r
+ }\r
+ //\r
+ // see if the prefixes are the same\r
+ //\r
+ if (canonicalBase.substring(0, 2).equals("\\\\")) {\r
+ //\r
+ // UNC file name, if target file doesn't also start with same\r
+ // server name, don't go there\r
+ int endPrefix = canonicalBase.indexOf('\\', 2);\r
+ String prefix1 = canonicalBase.substring(0, endPrefix);\r
+ String prefix2 = canonicalTarget.substring(0, endPrefix);\r
+ if (!prefix1.equals(prefix2)) {\r
+ return canonicalTarget;\r
+ }\r
+ } else {\r
+ if (canonicalBase.substring(1, 3).equals(":\\")) {\r
+ int endPrefix = 2;\r
+ String prefix1 = canonicalBase.substring(0, endPrefix);\r
+ String prefix2 = canonicalTarget.substring(0, endPrefix);\r
+ if (!prefix1.equals(prefix2)) {\r
+ return canonicalTarget;\r
+ }\r
+ } else {\r
+ if (canonicalBase.charAt(0) == '/') {\r
+ if (canonicalTarget.charAt(0) != '/') {\r
+ return canonicalTarget;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ char separator = File.separatorChar;\r
+ int lastSeparator = -1;\r
+ int minLength = canonicalBase.length();\r
+ if (canonicalTarget.length() < minLength) {\r
+ minLength = canonicalTarget.length();\r
+ }\r
+ int firstDifference = minLength + 1;\r
+ //\r
+ // walk to the shorter of the two paths\r
+ // finding the last separator they have in common\r
+ for (int i = 0; i < minLength; i++) {\r
+ if (canonicalTarget.charAt(i) == canonicalBase.charAt(i)) {\r
+ if (canonicalTarget.charAt(i) == separator) {\r
+ lastSeparator = i;\r
+ }\r
+ } else {\r
+ firstDifference = lastSeparator + 1;\r
+ break;\r
+ }\r
+ }\r
+ StringBuffer relativePath = new StringBuffer(50);\r
+ //\r
+ // walk from the first difference to the end of the base\r
+ // adding "../" for each separator encountered\r
+ //\r
+ if (canonicalBase.length() > firstDifference) {\r
+ relativePath.append("..");\r
+ for (int i = firstDifference; i < canonicalBase.length(); i++) {\r
+ if (canonicalBase.charAt(i) == separator) {\r
+ relativePath.append(separator);\r
+ relativePath.append("..");\r
+ }\r
+ }\r
+ }\r
+ if (canonicalTarget.length() > firstDifference) {\r
+ //\r
+ // append the rest of the target\r
+ //\r
+ //\r
+ if (relativePath.length() > 0) {\r
+ relativePath.append(separator);\r
+ }\r
+ relativePath.append(canonicalTarget.substring(firstDifference));\r
+ }\r
+ return relativePath.toString();\r
+ } catch (IOException ex) {\r
+ }\r
+ return targetFile.toString();\r
+ }\r
+ public static boolean isActive(Project p, String ifCond, String unlessCond)\r
+ throws BuildException {\r
+ if (ifCond != null) {\r
+ String ifValue = p.getProperty(ifCond);\r
+ if (ifValue == null) {\r
+ return false;\r
+ } else {\r
+ if (ifValue.equals("false") || ifValue.equals("no")) {\r
+ throw new BuildException("if condition \"" + ifCond\r
+ + "\" has suspicious value \"" + ifValue);\r
+ }\r
+ }\r
+ }\r
+ if (unlessCond != null) {\r
+ String unlessValue = p.getProperty(unlessCond);\r
+ if (unlessValue != null) {\r
+ if (unlessValue.equals("false") || unlessValue.equals("no")) {\r
+ throw new BuildException("unless condition \"" + unlessCond\r
+ + "\" has suspicious value \"" + unlessValue);\r
+ }\r
+ return false;\r
+ }\r
+ }\r
+ return true;\r
+ }\r
+ /**\r
+ * Parse a string containing directories into an File[]\r
+ * \r
+ * @param path\r
+ * path string, for example ".;c:\something\include"\r
+ * @param delim\r
+ * delimiter, typically ; or :\r
+ */\r
+ public static File[] parsePath(String path, String delim) {\r
+ Vector libpaths = new Vector();\r
+ int delimPos = 0;\r
+ for (int startPos = 0; startPos < path.length(); startPos = delimPos\r
+ + delim.length()) {\r
+ delimPos = path.indexOf(delim, startPos);\r
+ if (delimPos < 0) {\r
+ delimPos = path.length();\r
+ }\r
+ //\r
+ // don't add an entry for zero-length paths\r
+ //\r
+ if (delimPos > startPos) {\r
+ String dirName = path.substring(startPos, delimPos);\r
+ File dir = new File(dirName);\r
+ if (dir.exists() && dir.isDirectory()) {\r
+ libpaths.addElement(dir);\r
+ }\r
+ }\r
+ }\r
+ File[] paths = new File[libpaths.size()];\r
+ libpaths.copyInto(paths);\r
+ return paths;\r
+ }\r
+ /**\r
+ * This method is exposed so test classes can overload and test the\r
+ * arguments without actually spawning the compiler\r
+ */\r
+ public static int runCommand(CCTask task, File workingDir,\r
+ String[] cmdline, boolean newEnvironment, Environment env)\r
+ throws BuildException {\r
+ try {\r
+ task.log(Commandline.toString(cmdline), Project.MSG_VERBOSE);\r
+ Execute exe = new Execute(new LogStreamHandler(task,\r
+ Project.MSG_INFO, Project.MSG_ERR));\r
+ if (System.getProperty("os.name").equals("OS/390"))\r
+ exe.setVMLauncher(false);\r
+ exe.setAntRun(task.getProject());\r
+ exe.setCommandline(cmdline);\r
+ exe.setWorkingDirectory(workingDir);\r
+ if (env != null) {\r
+ String[] environment = env.getVariables();\r
+ if (environment != null) {\r
+ for (int i = 0; i < environment.length; i++) {\r
+ task.log("Setting environment variable: "\r
+ + environment[i], Project.MSG_VERBOSE);\r
+ }\r
+ }\r
+ exe.setEnvironment(environment);\r
+ }\r
+ exe.setNewenvironment(newEnvironment);\r
+ return exe.execute();\r
+ } catch (java.io.IOException exc) {\r
+ throw new BuildException("Could not launch " + cmdline[0] + ": "\r
+ + exc, task.getLocation());\r
+ }\r
+ }\r
+ /**\r
+ * Compares the contents of 2 arrays for equaliy.\r
+ */\r
+ public static boolean sameList(Object[] a, Object[] b) {\r
+ if (a == null || b == null || a.length != b.length) {\r
+ return false;\r
+ }\r
+ for (int i = 0; i < a.length; i++) {\r
+ if (!a[i].equals(b[i])) {\r
+ return false;\r
+ }\r
+ }\r
+ return true;\r
+ }\r
+ /**\r
+ * Compares the contents of an array and a Vector for equality.\r
+ */\r
+ public static boolean sameList(Vector v, Object[] a) {\r
+ if (v == null || a == null || v.size() != a.length) {\r
+ return false;\r
+ }\r
+ for (int i = 0; i < a.length; i++) {\r
+ Object o = a[i];\r
+ if (!o.equals(v.elementAt(i))) {\r
+ return false;\r
+ }\r
+ }\r
+ return true;\r
+ }\r
+ /**\r
+ * Compares the contents of an array and a Vector for set equality. Assumes\r
+ * input array and vector are sets (i.e. no duplicate entries)\r
+ */\r
+ public static boolean sameSet(Object[] a, Vector b) {\r
+ if (a == null || b == null || a.length != b.size()) {\r
+ return false;\r
+ }\r
+ if (a.length == 0) {\r
+ return true;\r
+ }\r
+ // Convert the array into a set\r
+ Hashtable t = new Hashtable();\r
+ for (int i = 0; i < a.length; i++) {\r
+ t.put(a[i], a[i]);\r
+ }\r
+ for (int i = 0; i < b.size(); i++) {\r
+ Object o = b.elementAt(i);\r
+ if (t.remove(o) == null) {\r
+ return false;\r
+ }\r
+ }\r
+ return (t.size() == 0);\r
+ }\r
+ /**\r
+ * Converts a vector to a string array.\r
+ */\r
+ public static String[] toArray(Vector src) {\r
+ String[] retval = new String[src.size()];\r
+ src.copyInto(retval);\r
+ return retval;\r
+ }\r
+ /**\r
+ * Replaces any embedded quotes in the string so that the value can be\r
+ * placed in an attribute in an XML file\r
+ * \r
+ * @param attrValue\r
+ * value to be expressed\r
+ * @return equivalent attribute literal\r
+ * \r
+ */\r
+ public static String xmlAttribEncode(String attrValue) {\r
+ int quotePos = attrValue.indexOf('\"');\r
+ if (quotePos < 0) {\r
+ return attrValue;\r
+ }\r
+ int startPos = 0;\r
+ StringBuffer buf = new StringBuffer(attrValue.length() + 20);\r
+ while (quotePos >= 0) {\r
+ buf.append(attrValue.substring(startPos, quotePos));\r
+ buf.append(""");\r
+ startPos = quotePos + 1;\r
+ quotePos = attrValue.indexOf('\"', startPos);\r
+ }\r
+ buf.append(attrValue.substring(startPos));\r
+ return buf.toString();\r
+ }\r
+}\r