package com.github.mustachejava.resolver;

import com.github.mustachejava.MustacheException;
import com.github.mustachejava.MustacheResolver;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

/* JADX INFO: loaded from: classes.dex */
public class FileSystemResolver implements MustacheResolver {
    private final File fileRoot;

    public FileSystemResolver() {
        this.fileRoot = null;
    }

    public FileSystemResolver(File file) {
        if (!file.exists()) {
            throw new MustacheException(file + " does not exist");
        }
        if (!file.isDirectory()) {
            throw new MustacheException(file + " is not a directory");
        }
        this.fileRoot = file;
    }

    @Override // com.github.mustachejava.MustacheResolver
    public Reader getReader(String str) {
        FileInputStream fileInputStream;
        File file = this.fileRoot == null ? new File(str) : new File(this.fileRoot, str);
        if (file.exists() && file.isFile()) {
            try {
                File file2 = this.fileRoot;
                if (file2 == null) {
                    file2 = new File("");
                }
                File canonicalFile = file2.getCanonicalFile();
                File canonicalFile2 = file.getCanonicalFile();
                do {
                    canonicalFile2 = canonicalFile2.getParentFile();
                    if (canonicalFile2 == null) {
                        break;
                    }
                } while (!canonicalFile2.equals(canonicalFile));
                if (canonicalFile2 == null) {
                    throw new MustacheException("File not under root: " + canonicalFile.getAbsolutePath());
                }
                fileInputStream = new FileInputStream(file);
            } catch (IOException e) {
                throw new MustacheException("Found file, could not open: " + file, e);
            }
        } else {
            fileInputStream = null;
        }
        if (fileInputStream != null) {
            return new BufferedReader(new InputStreamReader(fileInputStream, StandardCharsets.UTF_8));
        }
        return null;
    }
}
