1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use crate::{zalgo_decode, zalgo_encode, zalgo_wrap_python, UnencodableByteError};
use std::error::Error;

use std::{
    fmt, fs, io,
    path::{Path, PathBuf},
};

use core::str::Utf8Error;

/// Encodes the contents of the file and stores the result in another file.
/// If carriage return characters are found it will print a message and
/// attempt to encode the file anyway by ignoring them.
pub fn encode_file<P: AsRef<Path>>(in_file: P, out_file: P) -> Result<(), UnencodableFileError> {
    fn inner(in_file: &Path, out_file: &Path) -> Result<(), UnencodableFileError> {
        let mut string_to_encode = fs::read_to_string(in_file)?;

        if string_to_encode.contains('\t') {
            eprintln!("found tabs in the file, replacing with four spaces");
            string_to_encode = string_to_encode.replace('\t', "    ");
        }

        if string_to_encode.contains('\r') {
            eprintln!(
                r"file contains the carriage return character (\r). Will attempt to encode the file anyway by ignoring it. This may result in a different file when decoded"
            );
            string_to_encode = string_to_encode.replace('\r', "");
        }

        let mut out_path = PathBuf::new();
        out_path.push(out_file);

        if out_path.exists() {
            return Err(UnencodableFileError::OutputFileExists);
        }

        fs::File::create(out_file)?;
        fs::write(out_file, zalgo_encode(&string_to_encode)?)?;
        Ok(())
    }

    inner(in_file.as_ref(), out_file.as_ref())
}

/// Decodes the contents of a file that has been encoded with [`encode_file`]
/// and stores the result in another file.
pub fn decode_file<P: AsRef<Path>>(in_file: P, out_file: P) -> Result<(), UndecodableFileError> {
    fn inner(in_file: &Path, out_file: &Path) -> Result<(), UndecodableFileError> {
        let mut string_to_decode = fs::read_to_string(in_file)?;

        if string_to_decode.contains('\r') {
            eprintln!(
                r"file contains the carriage return character (\r). Will attempt to decode the file anyway by ignoring it"
            );
            string_to_decode = string_to_decode.replace('\r', "");
        }

        let decoded_string = zalgo_decode(&string_to_decode)?;

        let mut out_path = PathBuf::new();
        out_path.push(out_file);

        if out_path.exists() {
            return Err(UndecodableFileError::OutputFileExists);
        }

        fs::File::create(out_file)?;
        fs::write(out_file, decoded_string)?;
        Ok(())
    }

    inner(in_file.as_ref(), out_file.as_ref())
}

/// Encodes the contents of the given Python source file and stores the result wrapped in
/// a decoder in another file. This new file retains the functionality of the original.
/// If the source file contains carriage return characters this function will print a
/// message and then attempt to encode it anyway by ignoring them.
/// # Notes
/// The resulting python file may not work correctly on python versions before 3.10,
/// (see [this github issue](https://github.com/DaCoolOne/DumbIdeas/issues/1)).
pub fn wrap_python_file<P: AsRef<Path>>(
    in_file: P,
    out_file: P,
) -> Result<(), UnencodableFileError> {
    fn inner(in_file: &Path, out_file: &Path) -> Result<(), UnencodableFileError> {
        let mut string_to_encode = fs::read_to_string(in_file)?;

        if string_to_encode.contains('\t') {
            eprintln!("found tabs in the file, replacing with four spaces");
            string_to_encode = string_to_encode.replace('\t', "    ");
        }

        if string_to_encode.contains('\r') {
            eprintln!(
                r"file contains the carriage return character (\r). Will attempt to encode the file anyway by ignoring it. This may result in a different file when decoded"
            );
            string_to_encode = string_to_encode.replace('\r', "");
        }

        let mut out_path = PathBuf::new();
        out_path.push(out_file);

        if out_path.exists() {
            return Err(UnencodableFileError::OutputFileExists);
        }

        fs::File::create(out_file)?;
        fs::write(out_file, zalgo_wrap_python(&string_to_encode)?)?;
        Ok(())
    }

    inner(in_file.as_ref(), out_file.as_ref())
}

/// The error returned by the encoding functions that
/// interact with the file system.
#[derive(Debug)]
pub enum UnencodableFileError {
    Io(io::Error),
    OutputFileExists,
    UnencodableContent(UnencodableByteError),
}

impl fmt::Display for UnencodableFileError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "{e}"),
            Self::UnencodableContent(e) => write!(f, "{e}"),
            Self::OutputFileExists => {
                write!(f, "a file with the given output name already exists")
            }
        }
    }
}

impl Error for UnencodableFileError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::UnencodableContent(e) => Some(e),
            Self::OutputFileExists => None,
        }
    }
}

impl From<io::Error> for UnencodableFileError {
    fn from(err: io::Error) -> Self {
        Self::Io(err)
    }
}

impl From<UnencodableByteError> for UnencodableFileError {
    fn from(err: UnencodableByteError) -> Self {
        Self::UnencodableContent(err)
    }
}

/// The error returned by the decoding functions that
/// interact with the file system.
#[derive(Debug)]
pub enum UndecodableFileError {
    Io(io::Error),
    OutputFileExists,
    DecodesToInvalidUnicode(Utf8Error),
}

impl fmt::Display for UndecodableFileError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "{e}"),
            Self::DecodesToInvalidUnicode(e) => write!(f, "{e}"),
            Self::OutputFileExists => {
                write!(f, "a file with the given output name already exists")
            }
        }
    }
}

impl Error for UndecodableFileError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::DecodesToInvalidUnicode(e) => Some(e),
            Self::OutputFileExists => None,
        }
    }
}

impl From<io::Error> for UndecodableFileError {
    fn from(err: io::Error) -> Self {
        Self::Io(err)
    }
}

impl From<Utf8Error> for UndecodableFileError {
    fn from(err: Utf8Error) -> Self {
        Self::DecodesToInvalidUnicode(err)
    }
}