comparison graal/com.oracle.truffle.ruby.runtime/src/com/oracle/truffle/ruby/runtime/core/RubyFile.java @ 13514:0fbee3eb71f0

Ruby: import project.
author Chris Seaton <chris.seaton@oracle.com>
date Mon, 06 Jan 2014 17:12:09 +0000
parents
children
comparison
equal deleted inserted replaced
13513:64a23ce736a0 13514:0fbee3eb71f0
1 /*
2 * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. This
3 * code is released under a tri EPL/GPL/LGPL license. You can use it,
4 * redistribute it and/or modify it under the terms of the:
5 *
6 * Eclipse Public License version 1.0
7 * GNU General Public License version 2
8 * GNU Lesser General Public License version 2.1
9 */
10 package com.oracle.truffle.ruby.runtime.core;
11
12 import java.io.*;
13
14 import com.oracle.truffle.ruby.runtime.*;
15
16 /**
17 * Represents the Ruby {@code File} class.
18 */
19 public class RubyFile extends RubyObject {
20
21 private final Reader reader;
22 private final Writer writer;
23
24 public RubyFile(RubyClass rubyClass, Reader reader, Writer writer) {
25 super(rubyClass);
26 this.reader = reader;
27 this.writer = writer;
28 }
29
30 public void close() {
31 if (reader != null) {
32 try {
33 reader.close();
34 } catch (IOException e) {
35 throw new RuntimeException(e);
36 }
37 }
38
39 if (writer != null) {
40 try {
41 writer.close();
42 } catch (IOException e) {
43 throw new RuntimeException(e);
44 }
45 }
46 }
47
48 public static String expandPath(String fileName) {
49 // TODO(cs): see the other expandPath
50
51 try {
52 return new File(fileName).getCanonicalPath();
53 } catch (IOException e) {
54 throw new RuntimeException(e);
55 }
56 }
57
58 public static String expandPath(String fileName, String dir) {
59 /*
60 * TODO(cs): this isn't quite correct - I think we want to collapse .., but we don't want to
61 * resolve symlinks etc. This might be where we want to start borrowing JRuby's
62 * implementation, but it looks quite tied to their data structures.
63 */
64
65 try {
66 return new File(dir, fileName).getCanonicalPath();
67 } catch (IOException e) {
68 throw new RuntimeException(e);
69 }
70 }
71
72 public static RubyFile open(RubyContext context, String fileName, String mode) {
73 Reader reader;
74 Writer writer;
75
76 if (mode.equals("rb")) {
77 try {
78 reader = new InputStreamReader(new FileInputStream(fileName));
79 } catch (FileNotFoundException e) {
80 throw new RuntimeException(e);
81 }
82
83 writer = null;
84 } else if (mode.equals("w")) {
85 reader = null;
86
87 try {
88 writer = new OutputStreamWriter(new FileOutputStream(fileName));
89 } catch (FileNotFoundException e) {
90 throw new RuntimeException(e);
91 }
92 } else {
93 throw new UnsupportedOperationException();
94 }
95
96 final RubyFile file = new RubyFile(context.getCoreLibrary().getFileClass(), reader, writer);
97
98 return file;
99 }
100
101 public Reader getReader() {
102 return reader;
103 }
104
105 public Writer getWriter() {
106 return writer;
107 }
108
109 }