~starkingdoms/starkingdoms

ref: 0fac9a1bdd12d37ebc02d2fa59a80dc41f5aa2f4 starkingdoms/crates/xtask/src/main.rs -rw-r--r-- 5.6 KiB
0fac9a1bcore restructuring 11 months ago
                                                                                
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
use std::env::{args, var};
use std::error::Error;
use std::fs;
use std::io::Read;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, exit};
use std::sync::mpsc;
use std::sync::mpsc::TryRecvError;
use std::thread::sleep;
use std::time::Duration;
use colored::Colorize;
use notify::{Event, EventKind, RecursiveMode, Watcher};
use tiny_http::Server;
use wasm_pack::command::build::{BuildOptions, Target};
use wasm_pack::command::run_wasm_pack;
use wasm_pack::progressbar::LogLevel;

fn workspace_dir() -> PathBuf {
    let output = std::process::Command::new(env!("CARGO"))
        .arg("locate-project")
        .arg("--workspace")
        .arg("--message-format=plain")
        .output()
        .unwrap()
        .stdout;
    let cargo_path = Path::new(std::str::from_utf8(&output).unwrap().trim());
    cargo_path.parent().unwrap().to_path_buf()
}

fn build_client() -> anyhow::Result<()> {
    let cli = wasm_pack::Cli {
        cmd: wasm_pack::command::Command::Build(BuildOptions {
            path: Some(workspace_dir().join("crates/client")),
            scope: None,
            mode: Default::default(),
            disable_dts: false,
            weak_refs: false,
            reference_types: false,
            target: Target::Web,
            debug: false,
            dev: false,
            release: false,
            profiling: false,
            out_dir: "pkg".to_string(),
            out_name: None,
            no_pack: false,
            no_opt: true,
            extra_options: vec![],
        }),
        verbosity: 0,
        quiet: true,
        log_level: LogLevel::Error,
    };
    run_wasm_pack(cli.cmd)
}

fn try_build_client() -> bool {
    match build_client() {
        Ok(_) => {
            println!("{} -- Client package built successfully", "✓ Success".green().bold());
            true
        },
        Err(e) => {
            eprintln!("{} -- Client package failed to build: {}", "✗ Failed".red().bold(), e);
            false
        }
    }
}

fn start_server() {
    let server = Server::http(var("BIND").unwrap_or("[::]:8000".to_string())).unwrap();
    for req in server.incoming_requests() {
        let mut path = Path::new(req.url());
        if path == Path::new("/") {
            path = Path::new("/index.html");
        }
        
        let path = path.strip_prefix(Path::new("/")).unwrap();
        
        let full_path = workspace_dir().join("crates/client").join(path);
        
        let content = match fs::read(full_path) {
            Ok(r) => r,
            Err(_) => { continue; }
        };
        
        
    }
}

fn main() {
    let mut args = args();
    let subcommand = args.nth(1).unwrap();

    match subcommand.as_str() {
        "client" => {
            if !try_build_client() {
                exit(1);
            }
        },
        "watch" | "serve" => {
            let serve = subcommand == "serve";

            if serve {
                std::thread::spawn(start_server);
            }

            try_build_client();
            let (tx, rx) = mpsc::channel::<notify::Result<Event>>();

            // Use recommended_watcher() to automatically select the best implementation
            // for your platform. The `EventHandler` passed to this constructor can be a
            // closure, a `std::sync::mpsc::Sender`, a `crossbeam_channel::Sender`, or
            // another type the trait is implemented for.
            let mut watcher = notify::recommended_watcher(tx).unwrap();

            // Add a path to be watched. All files and directories at that path and
            // below will be monitored for changes.
            watcher.watch(&workspace_dir().join("crates"), RecursiveMode::Recursive).unwrap();
            println!("{}", "[Watch] 🛈 Watching for file changes".blue().bold());
            // Block forever, printing out events as they come in

            let mut needs_rebuild = false;

            loop {
                let res = rx.try_recv();

                let res = match res {
                    Ok(r) => r,
                    Err(TryRecvError::Empty) => {
                        if needs_rebuild {
                            // wait 1s then check again, then rebuild
                            sleep(Duration::from_secs(1));
                            if let Ok(r) = rx.try_recv() {
                                r
                            } else {
                                try_build_client();
                                needs_rebuild = false;

                                rx.recv().unwrap()
                            }
                        } else {
                            rx.recv().unwrap()
                        }
                    },
                    Err(TryRecvError::Disconnected) => panic!("{:?}", TryRecvError::Disconnected)
                };

                match res {
                    Ok(event) => {
                        if let EventKind::Modify(_) = event.kind {
                            let mut has_non_generated_update = false;
                            for path in &event.paths {
                                if !path.to_str().unwrap().contains("client/pkg") && !path.to_str().unwrap().ends_with("~") {
                                    needs_rebuild = true;
                                }
                            }
                        }

                    },
                    Err(e) => {
                        eprintln!("{} -- Error watching for files: {}", "[Watch] ✗ Error".red().bold(), e);
                    },
                }
            }
        },
        _ => panic!("unsupported command")
    }
}