package com.atlassian.bitbucket.mesh.git.transcode;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Describes a component which can read in a file at a given path and transcode its text to UTF-8. If the text is
 * already UTF-8, or the encoding cannot be detected, the file will be streamed as-is. If the file is binary its
 * contents will be <i>dropped</i> and marker text will be streamed instead.
 * <p>
 * This component is specifically geared toward allowing {@code git blame} and {@code git diff} to handle non-UTF-8
 * files by transcoding their text. The {@code transcode.pl} script can be registered as a {@code textconv} script
 * and used to call back into the system, via the {@link TranscodeServer}, to transcode files to UTF-8.
 */
public interface Transcoder {

    /**
     * Performs encoding detection and transcoding on the specified path, writing UTF-8 data to the provided
     * {@code OutputStream}. To prevent using transcoding to read arbitrary files on the server only files in
     * {@code STASH_HOME/tmp} can be transcoded.
     *
     * @param path the path at which encoding is detected and transcoding happens
     * @param stream the stream that will be written to
     * @throws IllegalArgumentException if no {@code path} is provided, the provided {@code path} is not in
     *                                  {@code STASH_HOME/tmp} or the {@code path} does not exist
     * @throws IOException if the file at {@code path} cannot be read, or if the transcoded data cannot be
     *                     written to the {@code OutputStream}
     */
    void transcode(@Nonnull String path, @Nonnull OutputStream stream) throws IOException;
}
