001/*
002 * Anarres C Preprocessor
003 * Copyright (c) 2007-2015, Shevek
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
014 * or implied.  See the License for the specific language governing
015 * permissions and limitations under the License.
016 */
017package org.anarres.cpp;
018
019import java.io.File;
020import java.io.IOException;
021
022/**
023 * A virtual filesystem implementation using java.io in a virtual
024 * chroot.
025 */
026public class ChrootFileSystem implements VirtualFileSystem {
027
028    private File root;
029
030    public ChrootFileSystem(File root) {
031        this.root = root;
032    }
033
034    @Override
035    public VirtualFile getFile(String path) {
036        return new ChrootFile(path);
037    }
038
039    @Override
040    public VirtualFile getFile(String dir, String name) {
041        return new ChrootFile(dir, name);
042    }
043
044    private class ChrootFile extends File implements VirtualFile {
045
046        private File rfile;
047
048        public ChrootFile(String path) {
049            super(path);
050        }
051
052        public ChrootFile(String dir, String name) {
053            super(dir, name);
054        }
055
056        /* private */
057        public ChrootFile(File dir, String name) {
058            super(dir, name);
059        }
060
061        @Override
062        public ChrootFile getParentFile() {
063            return new ChrootFile(getParent());
064        }
065
066        @Override
067        public ChrootFile getChildFile(String name) {
068            return new ChrootFile(this, name);
069        }
070
071        @Override
072        public boolean isFile() {
073            File real = new File(root, getPath());
074            return real.isFile();
075        }
076
077        @Override
078        public Source getSource() throws IOException {
079            return new FileLexerSource(new File(root, getPath()),
080                    getPath());
081        }
082    }
083
084}