Use CommandSession.currentDir()

git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@1735997 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/gogo/jline/pom.xml b/gogo/jline/pom.xml
index ecb67b1..350a913 100644
--- a/gogo/jline/pom.xml
+++ b/gogo/jline/pom.xml
@@ -31,6 +31,7 @@
     <properties>
         <!-- Skip because of NPE -->
         <animal.sniffer.skip>true</animal.sniffer.skip>
+        <felix.java.version>8</felix.java.version>
     </properties>
     <dependencies>
         <dependency>
diff --git a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Builtin.java b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Builtin.java
index a4fc3ef..7153dbf 100644
--- a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Builtin.java
+++ b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Builtin.java
@@ -20,8 +20,6 @@
 
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.StringWriter;
@@ -29,6 +27,11 @@
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.OpenOption;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashSet;
@@ -224,9 +227,16 @@
         BufferedWriter fw = null;
 
         if (args.size() == 1) {
-            String path = args.get(0);
-            File file = new File(Posix._pwd(session), path);
-            fw = new BufferedWriter(new FileWriter(file, opt.isSet("append")));
+            Path path = session.currentDir().resolve(args.get(0));
+            Set<OpenOption> options = new HashSet<>();
+            options.add(StandardOpenOption.WRITE);
+            options.add(StandardOpenOption.CREATE);
+            if (opt.isSet("append")) {
+                options.add(StandardOpenOption.APPEND);
+            } else {
+                options.add(StandardOpenOption.TRUNCATE_EXISTING);
+            }
+            fw = Files.newBufferedWriter(path, StandardCharsets.UTF_8, options.toArray(new OpenOption[options.size()]));
         }
 
         StringWriter sw = new StringWriter();
diff --git a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/JLineCommands.java b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/JLineCommands.java
index 498e12e..294011e 100644
--- a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/JLineCommands.java
+++ b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/JLineCommands.java
@@ -20,7 +20,6 @@
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
-import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintStream;
@@ -105,7 +104,7 @@
     }
 
     public void nano(final CommandSession session, String[] argv) throws Exception {
-        commands.nano(Shell.getTerminal(session), System.out, System.err, Shell.cwd(session), argv);
+        commands.nano(Shell.getTerminal(session), System.out, System.err, session.currentDir(), argv);
     }
 
     public void watch(final CommandSession session, String[] argv) throws IOException, InterruptedException {
@@ -169,7 +168,7 @@
     }
 
     public void less(CommandSession session, String[] argv) throws IOException, InterruptedException {
-        commands.less(Shell.getTerminal(session), System.out, System.err, Shell.cwd(session), argv);
+        commands.less(Shell.getTerminal(session), System.out, System.err, session.currentDir(), argv);
     }
 
     public void history(CommandSession session, String[] argv) throws IOException {
@@ -209,7 +208,7 @@
         ParsedLine line = Shell.getParsedLine(session);
         LineReader reader = Shell.getReader(session);
         List<Candidate> candidates = new ArrayList<>();
-        new FilesCompleter(new File(Shell.cwd(session))).complete(reader, line, candidates);
+        new FilesCompleter(session.currentDir()).complete(reader, line, candidates);
         return candidates;
     }
 
@@ -217,7 +216,7 @@
         ParsedLine line = Shell.getParsedLine(session);
         LineReader reader = Shell.getReader(session);
         List<Candidate> candidates = new ArrayList<>();
-        new DirectoriesCompleter(new File(Shell.cwd(session))).complete(reader, line, candidates);
+        new DirectoriesCompleter(session.currentDir()).complete(reader, line, candidates);
         return candidates;
     }
 
diff --git a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Posix.java b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Posix.java
index 05c4908..4b90b7e 100644
--- a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Posix.java
+++ b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Posix.java
@@ -20,11 +20,11 @@
 
 import java.io.BufferedReader;
 import java.io.File;
-import java.io.FileFilter;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
-import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -45,21 +45,6 @@
 public class Posix {
     static final String[] functions = {"cat", "echo", "grep", "sort", "sleep", "cd", "pwd", "ls"};
 
-    static final String CWD = "_cwd";
-
-    public static File _pwd(CommandSession session) {
-        try {
-            File cwd = (File) session.get(CWD);
-            if (cwd == null) {
-                cwd = new File(".").getCanonicalFile();
-                session.put(CWD, cwd);
-            }
-            return cwd;
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
     public static void sort(CommandSession session, String[] argv) throws IOException {
         final String[] usage = {
                 "sort -  writes sorted standard input to standard output.",
@@ -86,7 +71,7 @@
         if (!args.isEmpty()) {
             for (String filename : args) {
                 BufferedReader reader = new BufferedReader(new InputStreamReader(
-                        Shell.cwd(session).resolve(filename).toURL().openStream()));
+                        session.currentDir().toUri().resolve(filename).toURL().openStream()));
                 try {
                     read(reader, lines);
                 } finally {
@@ -261,13 +246,7 @@
         }
     }
 
-    private static <T> void addAll(List<? super T> list, T[] array) {
-        if (array != null) {
-            Collections.addAll(list, array);
-        }
-    }
-
-    public File pwd(CommandSession session, String[] argv) throws IOException {
+    public Path pwd(CommandSession session, String[] argv) throws IOException {
         final String[] usage = {
                 "pwd - get current directory",
                 "Usage: pwd [OPTIONS]",
@@ -282,16 +261,10 @@
             System.err.println("usage: pwd");
             return null;
         }
-        File cwd = (File) session.get(CWD);
-        if (cwd == null) {
-            cwd = new File(".").getCanonicalFile();
-            session.put(CWD, cwd);
-        }
-        return cwd;
+        return session.currentDir();
     }
 
-    public File cd(CommandSession session, String[] argv)
-            throws IOException {
+    public void cd(CommandSession session, String[] argv) throws IOException {
         final String[] usage = {
                 "cd - get current directory",
                 "Usage: cd [OPTIONS] DIRECTORY",
@@ -300,29 +273,23 @@
         Options opt = Options.compile(usage).parse(argv);
         if (opt.isSet("help")) {
             opt.usage(System.err);
-            return null;
+            return;
         }
         if (opt.args().size() != 1) {
             System.err.println("usage: cd DIRECTORY");
-            return null;
+            return;
         }
-        File cwd = pwd(session, new String[0]);
-        String dir = opt.args().get(0);
-
-        URI curUri = cwd.toURI();
-        URI newUri = curUri.resolve(dir);
-
-        cwd = new File(newUri);
-        if (!cwd.exists()) {
+        Path cwd = session.currentDir();
+        cwd = cwd.resolve(opt.args().get(0)).toAbsolutePath();
+        if (!Files.exists(cwd)) {
             throw new IOException("Directory does not exist");
-        } else if (!cwd.isDirectory()) {
+        } else if (!Files.isDirectory(cwd)) {
             throw new IOException("Target is not a directory");
         }
-        session.put(CWD, cwd.getCanonicalFile());
-        return cwd;
+        session.currentDir(cwd);
     }
 
-    public Collection<File> ls(CommandSession session, String[] argv) throws IOException {
+    public Collection<Path> ls(CommandSession session, String[] argv) throws IOException {
         final String[] usage = {
                 "ls - list files",
                 "Usage: ls [OPTIONS] PATTERNS...",
@@ -336,8 +303,7 @@
         if (opt.args().isEmpty()) {
             opt.args().add("*");
         }
-        opt.args().remove(0);
-        List<File> files = new ArrayList<File>();
+        List<Path> files = new ArrayList<>();
         for (String pattern : opt.args()) {
             pattern = ((pattern == null) || (pattern.length() == 0)) ? "." : pattern;
             pattern = ((pattern.charAt(0) != File.separatorChar) && (pattern.charAt(0) != '.'))
@@ -346,29 +312,28 @@
             String parent = (idx < 0) ? "." : pattern.substring(0, idx + 1);
             String target = (idx < 0) ? pattern : pattern.substring(idx + 1);
 
-            File actualParent = ((parent.charAt(0) == File.separatorChar)
-                    ? new File(parent)
-                    : new File(pwd(session, new String[0]), parent)).getCanonicalFile();
+            Path actualParent = session.currentDir().resolve(parent).normalize();
 
             idx = target.indexOf(File.separatorChar, idx);
             boolean isWildcarded = (target.indexOf('*', idx) >= 0);
             if (isWildcarded) {
-                if (!actualParent.exists()) {
+                if (!Files.exists(actualParent)) {
                     throw new IOException("File does not exist");
                 }
                 final List<String> pieces = parseSubstring(target);
-                addAll(files, actualParent.listFiles(new FileFilter() {
-                    public boolean accept(File pathname) {
-                        return compareSubstring(pieces, pathname.getName());
-                    }
-                }));
+                Files.list(actualParent)
+                        .filter(p -> compareSubstring(pieces, p.getFileName().toString()))
+                        .map(actualParent::relativize)
+                        .forEach(files::add);
             } else {
-                File actualTarget = new File(actualParent, target).getCanonicalFile();
-                if (!actualTarget.exists()) {
+                Path actualTarget = actualParent.resolve(target);
+                if (!Files.exists(actualTarget)) {
                     throw new IOException("File does not exist");
                 }
-                if (actualTarget.isDirectory()) {
-                    addAll(files, actualTarget.listFiles());
+                if (Files.isDirectory(actualTarget)) {
+                    Files.list(actualTarget)
+                            .map(actualTarget::relativize)
+                            .forEach(files::add);
                 } else {
                     files.add(actualTarget);
                 }
@@ -397,14 +362,14 @@
             args = Collections.singletonList("-");
         }
 
-        URI cwd = Shell.cwd(session);
+        Path cwd = session.currentDir();
         for (String arg : args) {
             InputStream is;
             if ("-".equals(arg)) {
                 is = System.in;
 
             } else {
-                is = cwd.resolve(arg).toURL().openStream();
+                is = cwd.toUri().resolve(arg).toURL().openStream();
             }
             cat(new BufferedReader(new InputStreamReader(is)), opt.isSet("n"));
         }
@@ -494,8 +459,8 @@
             InputStream in = null;
 
             try {
-                URI cwd = Shell.cwd(session);
-                in = (arg == null) ? System.in : cwd.resolve(arg).toURL().openStream();
+                Path cwd = session.currentDir();
+                in = (arg == null) ? System.in : cwd.resolve(arg).toUri().toURL().openStream();
 
                 BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
                 int line = 0;
diff --git a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Shell.java b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Shell.java
index d92fed6..367e6af 100644
--- a/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Shell.java
+++ b/gogo/jline/src/main/java/org/apache/felix/gogo/jline/Shell.java
@@ -188,10 +188,6 @@
         return (Set<String>) session.get(".variables");
     }
 
-    static URI cwd(CommandSession session) {
-        return Posix._pwd(session).toURI(); // _cwd is set by felixcommands:cd
-    }
-
     private static <T extends Annotation> T findAnnotation(Annotation[] anns,
                                                            Class<T> clazz) {
         for (int i = 0; (anns != null) && (i < anns.length); i++) {
@@ -255,6 +251,7 @@
         newSession.put("#TERM", (Function) (s, arguments) -> terminal.getType());
         newSession.put("#COLUMNS", (Function) (s, arguments) -> terminal.getWidth());
         newSession.put("#LINES", (Function) (s, arguments) -> terminal.getHeight());
+        newSession.put("#CWD", (Function) (s, arguments) -> s.currentDir().toString());
 
         LineReader reader = null;
         if (args.isEmpty() && interactive) {
@@ -338,7 +335,7 @@
                 }
                 program = buf;
             } else {
-                URI script = cwd(session).resolve(args.remove(0));
+                URI script = session.currentDir().toUri().resolve(args.remove(0));
 
                 // set script arguments
                 newSession.put("0", script);
@@ -371,7 +368,7 @@
     }
 
     public Object source(CommandSession session, String script) throws Exception {
-        URI uri = cwd(session).resolve(script);
+        URI uri = session.currentDir().toUri().resolve(script);
         session.put("0", uri);
         try {
             return session.execute(readScript(uri));