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
use kuchiki::{traits::TendrilSink, NodeRef};
use rayon::prelude::*;
use state::*;
use std::{
    fs,
    io::Read,
    path::{Path, PathBuf},
};

mod errors;
mod state;

pub struct PagebreakRunner {
    working_directory: PathBuf,
    source: PathBuf,
    output: PathBuf,
    pages: Option<Vec<SourcePage>>,
}

impl PagebreakRunner {
    pub fn new(working_directory: PathBuf, source: PathBuf, output: PathBuf) -> Self {
        PagebreakRunner {
            working_directory,
            source,
            output,
            pages: None,
        }
    }

    fn full_source_path(&self) -> PathBuf {
        let full_source_path = self.working_directory.join(&self.source);
        match fs::canonicalize(&full_source_path) {
            Ok(path) => path,
            Err(_) => {
                eprintln!(
                    "Pagebreak error: couldn't find source directory: {:?}",
                    full_source_path
                );
                std::process::exit(1);
            }
        }
    }

    fn full_output_path(&self) -> PathBuf {
        let full_output_path = self.working_directory.join(&self.output);
        fs::create_dir_all(&full_output_path).unwrap();
        match fs::canonicalize(&full_output_path) {
            Ok(path) => path,
            Err(_) => {
                eprintln!(
                    "Pagebreak error: couldn't create output directory: {:?}",
                    full_output_path
                );
                std::process::exit(1);
            }
        }
    }

    fn copy_source_to_output(&self) {
        // Not Yet Implemented
        // copy the source directory to the output directory
        // TODO: This also needs to clean up the output directory
        // fs::create_dir_all(&output_path).unwrap();
        // let options = CopyOptions::new();
        // copy(&source, &output_path, &options).unwrap();
    }

    fn read_pages(&mut self) {
        let source = self.full_source_path();
        let pages = read_pages(&source)
            .into_par_iter()
            .filter(|page| page.contains_pagination())
            .collect();
        self.pages = Some(pages);
    }

    fn paginate(&mut self) {
        let source = self.full_source_path();
        let output = self.full_output_path();
        let mut pages = self.pages.take().unwrap();
        pages.iter_mut().for_each(|page| {
            page.paginate(&source, &output);
        });
    }

    pub fn run(&mut self) {
        self.copy_source_to_output();
        self.read_pages();
        println!(
            "Pagebreak: Found {} pages with pagination",
            self.pages.as_ref().unwrap().len()
        );
        self.paginate();
    }
}

struct SourcePage {
    path: PathBuf,
    source: Option<String>,
}

impl SourcePage {
    fn contains_pagination(&self) -> bool {
        self.source.as_ref().unwrap().contains("data-pagebreak")
    }

    fn parse(&self) -> NodeRef {
        kuchiki::parse_html().one(self.source.as_ref().unwrap().as_str())
    }

    fn paginate(&self, input_path: &Path, output_path: &Path) {
        let file_path = self.path.strip_prefix(&input_path).unwrap();

        let mut state =
            PagebreakState::new(self.parse(), file_path.to_owned(), output_path.to_owned());

        state.hydrate();
        state.log_hydrated();
        state.paginate();
    }
}

fn read_pages(path: &Path) -> Vec<SourcePage> {
    let globwalker = globwalk::GlobWalkerBuilder::from_patterns(&path, &["*.html"])
        .build()
        .unwrap();

    let mut pages: Vec<SourcePage> = globwalker
        .map(|entry| {
            let entry = entry.unwrap();
            let path = entry.path().to_owned();

            SourcePage {
                path: path.to_path_buf(),
                source: None,
            }
        })
        .collect();

    pages.par_iter_mut().for_each(|page| {
        let mut file = fs::File::open(&page.path).unwrap();
        let mut content = String::new();
        file.read_to_string(&mut content).unwrap();

        page.source = Some(content);
    });

    pages
}

// #[cfg(test)]
// mod tests {
//     use super::*;

//     fn gfu(input: &PathBuf, url_format: &str, is_path: &str, when_num: usize) {
//         assert_eq!(
//             PathBuf::from(is_path),
//             get_file_url(input, url_format, when_num).unwrap()
//         );
//     }

//     #[test]
//     fn test_get_file_url() {
//         let input = PathBuf::from("about/index.html");
//         let url_format = "./page/:num/";
//         gfu(&input, url_format, "about/index.html", 0);
//         gfu(&input, url_format, "about/page/2/index.html", 1);

//         let input = PathBuf::from("index.html");
//         let url_format = "./page/:num/";
//         gfu(&input, url_format, "index.html", 0);
//         gfu(&input, url_format, "page/2/index.html", 1);

//         let input = PathBuf::from("a/b/c/index.html");
//         let url_format = "../../page/:num/";
//         gfu(&input, url_format, "a/b/c/index.html", 0);
//         gfu(&input, url_format, "a/page/2/index.html", 1);
//     }

//     #[test]
//     fn test_bad_file_url() {
//         let input = PathBuf::from("index.html");
//         let url_format = "../../page/:num/";
//         assert_eq!(
//             errors::PageErrorCode::ParentDir,
//             get_file_url(&input, url_format, 1).unwrap_err().code
//         );
//     }
// }