package com.semmle.util.trap.pathtransformers;

import java.io.File;

import com.semmle.util.files.FileUtil;
import com.semmle.util.process.Env;
import com.semmle.util.process.Env.Var;

public abstract class PathTransformer {
	public abstract String transform(String input);

	/**
	 * Convert a file to its path in the (code) database. Turns file paths into
	 * canonical, absolute, strings and normalises away Unix/Windows differences.
	 */
	public String fileAsDatabaseString(File file) {
		String path = file.getPath();
		// For a /!unknown-binary-location/... path, on Windows
		// the standard code wants to normalise it to
		// C:/!unknown-binary-location/...
		// which is particularly annoying for cross-platform test
		// output. We therefore handle it specially here.
		if (path.matches("^[/\\\\]!unknown-binary-location[/\\\\].*")) {
			return path.replace('\\', '/');
		}
		if (Boolean.valueOf(Env.systemEnv().get(Var.SEMMLE_PRESERVE_SYMLINKS)))
			path = FileUtil.simplifyPath(file);
		else
			path = FileUtil.tryMakeCanonical(file).getPath();
		return transform(FileUtil.normalisePath(path));
	}

	/**
	 * Utility method for extractors: Canonicalise the given path as required
	 * for the current extraction. Unlike {@link FileUtil#tryMakeCanonical(File)},
	 * this method is consistent with {@link #fileAsDatabaseString(File)}.
	 */
	public File canonicalFile(String path) {
		return new File(fileAsDatabaseString(new File(path)));
	}

	private static final PathTransformer DEFAULT_TRANSFORMER;
	static {
		String layout = Env.systemEnv().get(Var.SEMMLE_PATH_TRANSFORMER);
		if (layout == null)
			DEFAULT_TRANSFORMER = new NoopTransformer();
		else
			DEFAULT_TRANSFORMER = new ProjectLayoutTransformer(new File(layout));
	}

	public static PathTransformer std() {
		return DEFAULT_TRANSFORMER;
	}
}

@@ -525,18 +525,16 @@
 %09// For 
-a 
 /!unknow
@@ -554,21 +554,44 @@
 tion/...
+ and /modules/...%0A%09%09//
  path
+s
 , on Win
@@ -594,21 +594,16 @@
  Windows
-%0A%09%09//
  the sta
@@ -621,16 +621,21 @@
 wants to
+%0A%09%09//
  normali
@@ -641,18 +641,20 @@
 ise 
-it to%0A%09%09//
+them to e.g.
  C:/
@@ -775,18 +775,20 @@
  handle 
-i
 t
+hem
  special
@@ -824,16 +824,17 @@
 %5E%5B/%5C%5C%5C%5C%5D
+(
 !unknown
@@ -849,16 +849,25 @@
 location
+%7Cmodules)
 %5B/%5C%5C%5C%5C%5D.

Handle /modules/... paths specially too