Skip to main content

xtask/
dist.rs

1use anyhow::Context;
2use flate2::{Compression, write::GzEncoder};
3use std::{
4    fs::File,
5    io::{self, BufWriter},
6    path::{Path, PathBuf},
7};
8use time::OffsetDateTime;
9use xshell::{Cmd, Shell, cmd};
10use zip::{DateTime, ZipWriter, write::SimpleFileOptions};
11
12use crate::{
13    date_iso,
14    flags::{self, Malloc, PgoTrainingCrate},
15    project_root,
16    util::detect_target,
17};
18
19const VERSION_STABLE: &str = "0.3";
20const VERSION_NIGHTLY: &str = "0.4";
21const VERSION_DEV: &str = "0.5"; // keep this one in sync with `package.json`
22
23impl flags::Dist {
24    pub(crate) fn run(self, sh: &Shell) -> anyhow::Result<()> {
25        let stable = sh.var("GITHUB_REF").unwrap_or_default().as_str() == "refs/heads/release";
26
27        let project_root = project_root();
28        let target = Target::get(&project_root, sh);
29        let allocator = self.allocator();
30        let dist = project_root.join("dist");
31        sh.remove_path(&dist)?;
32        sh.create_dir(&dist)?;
33
34        if let Some(patch_version) = self.client_patch_version {
35            let version = if stable {
36                format!("{VERSION_STABLE}.{patch_version}")
37            } else {
38                // A hack to make VS Code prefer nightly over stable.
39                format!("{VERSION_NIGHTLY}.{patch_version}")
40            };
41            dist_server(
42                sh,
43                &format!("{version}-standalone"),
44                &target,
45                allocator,
46                self.pgo,
47                // Profiling requires debug information.
48                self.enable_profiling,
49            )?;
50            let release_tag = if stable { date_iso(sh)? } else { "nightly".to_owned() };
51            dist_client(sh, &version, &release_tag, &target)?;
52        } else {
53            dist_server(
54                sh,
55                "0.0.0-standalone",
56                &target,
57                allocator,
58                self.pgo,
59                // Profiling requires debug information.
60                self.enable_profiling,
61            )?;
62        }
63        Ok(())
64    }
65}
66
67fn dist_client(
68    sh: &Shell,
69    version: &str,
70    release_tag: &str,
71    target: &Target,
72) -> anyhow::Result<()> {
73    let bundle_path = Path::new("editors").join("code").join("server");
74    sh.create_dir(&bundle_path)?;
75    sh.copy_file(&target.server_path, &bundle_path)?;
76    if let Some(symbols_path) = &target.symbols_path {
77        sh.copy_file(symbols_path, &bundle_path)?;
78    }
79
80    let _d = sh.push_dir("./editors/code");
81
82    let mut patch = Patch::new(sh, "./package.json")?;
83    patch
84        .replace(
85            &format!(r#""version": "{VERSION_DEV}.0-dev""#),
86            &format!(r#""version": "{version}""#),
87        )
88        .replace(r#""releaseTag": null"#, &format!(r#""releaseTag": "{release_tag}""#))
89        .replace(r#""title": "$generated-start""#, "")
90        .replace(r#""title": "$generated-end""#, "")
91        .replace(r#""enabledApiProposals": [],"#, r#""#);
92    patch.commit(sh)?;
93
94    Ok(())
95}
96
97fn dist_server(
98    sh: &Shell,
99    release: &str,
100    target: &Target,
101    allocator: Malloc,
102    pgo: Option<PgoTrainingCrate>,
103    dev_rel: bool,
104) -> anyhow::Result<()> {
105    let _e = sh.push_env("CFG_RELEASE", release);
106    let _e = sh.push_env("CARGO_PROFILE_RELEASE_LTO", "thin");
107    let _e = sh.push_env("CARGO_PROFILE_RELEASE_CODEGEN_UNITS", "1");
108    let _e = sh.push_env("CARGO_PROFILE_DEV_REL_LTO", "thin");
109    let _e = sh.push_env("CARGO_PROFILE_DEV_REL_CODEGEN_UNITS", "1");
110
111    // Uncomment to enable debug info for releases. Note that:
112    //   * debug info is split on windows and macs, so it does nothing for those platforms,
113    //   * on Linux, this blows up the binary size from 8MB to 43MB, which is unreasonable.
114    // let _e = sh.push_env("CARGO_PROFILE_RELEASE_DEBUG", "1");
115
116    let features = allocator.to_features();
117
118    let cmd = build_command(sh, &target.name, features, dev_rel);
119    let pgo_profile = if let Some(train_crate) = pgo {
120        Some(crate::pgo::gather_pgo_profile(sh, cmd, &target.name, train_crate)?)
121    } else {
122        None
123    };
124
125    let mut cmd = build_command(sh, &target.name, features, dev_rel);
126    let mut rustflags = Vec::new();
127
128    if let Some(profile) = pgo_profile {
129        rustflags.push(format!("-Cprofile-use={}", profile.to_str().unwrap()));
130    }
131
132    if target.name.ends_with("-windows-msvc") {
133        // https://github.com/rust-lang/rust-analyzer/issues/20970
134        rustflags.push("-Ctarget-feature=+crt-static".to_owned());
135    }
136
137    if !rustflags.is_empty() {
138        cmd = cmd.env("RUSTFLAGS", rustflags.join(" "));
139    }
140    cmd.run().context("cannot build Rust Analyzer")?;
141
142    let dst = Path::new("dist").join(&target.artifact_name);
143    if target.name.contains("-windows-") {
144        zip(&target.server_path, target.symbols_path.as_ref(), &dst.with_extension("zip"))?;
145    } else {
146        gzip(&target.server_path, &dst.with_extension("gz"))?;
147    }
148
149    Ok(())
150}
151
152fn build_command<'a>(
153    sh: &'a Shell,
154    target_name: &str,
155    features: &[&str],
156    dev_rel: bool,
157) -> Cmd<'a> {
158    let profile = if dev_rel { "dev-rel" } else { "release" };
159    cmd!(
160        sh,
161        "cargo build --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --target {target_name} {features...} --profile {profile}"
162    )
163}
164
165fn gzip(src_path: &Path, dest_path: &Path) -> anyhow::Result<()> {
166    let mut encoder = GzEncoder::new(File::create(dest_path)?, Compression::best());
167    let mut input = io::BufReader::new(File::open(src_path)?);
168    io::copy(&mut input, &mut encoder)?;
169    encoder.finish()?;
170    Ok(())
171}
172
173fn zip(src_path: &Path, symbols_path: Option<&PathBuf>, dest_path: &Path) -> anyhow::Result<()> {
174    let file = File::create(dest_path)?;
175    let mut writer = ZipWriter::new(BufWriter::new(file));
176    writer.start_file(
177        src_path.file_name().unwrap().to_str().unwrap(),
178        SimpleFileOptions::default()
179            .last_modified_time(
180                DateTime::try_from(OffsetDateTime::from(std::fs::metadata(src_path)?.modified()?))
181                    .unwrap(),
182            )
183            .unix_permissions(0o755)
184            .compression_method(zip::CompressionMethod::Deflated)
185            .compression_level(Some(9)),
186    )?;
187    let mut input = io::BufReader::new(File::open(src_path)?);
188    io::copy(&mut input, &mut writer)?;
189    if let Some(symbols_path) = symbols_path {
190        writer.start_file(
191            symbols_path.file_name().unwrap().to_str().unwrap(),
192            SimpleFileOptions::default()
193                .last_modified_time(
194                    DateTime::try_from(OffsetDateTime::from(
195                        std::fs::metadata(src_path)?.modified()?,
196                    ))
197                    .unwrap(),
198                )
199                .compression_method(zip::CompressionMethod::Deflated)
200                .compression_level(Some(9)),
201        )?;
202        let mut input = io::BufReader::new(File::open(symbols_path)?);
203        io::copy(&mut input, &mut writer)?;
204    }
205    writer.finish()?;
206    Ok(())
207}
208
209struct Target {
210    name: String,
211    server_path: PathBuf,
212    symbols_path: Option<PathBuf>,
213    artifact_name: String,
214}
215
216impl Target {
217    fn get(project_root: &Path, sh: &Shell) -> Self {
218        let name = detect_target(sh);
219        let out_path = project_root.join("target").join(&name).join("release");
220        let (exe_suffix, symbols_path) = if name.contains("-windows-") {
221            (".exe".into(), Some(out_path.join("rust_analyzer.pdb")))
222        } else {
223            (String::new(), None)
224        };
225        let server_path = out_path.join(format!("rust-analyzer{exe_suffix}"));
226        let artifact_name = format!("rust-analyzer-{name}{exe_suffix}");
227        Self { name, server_path, symbols_path, artifact_name }
228    }
229}
230
231struct Patch {
232    path: PathBuf,
233    original_contents: String,
234    contents: String,
235}
236
237impl Patch {
238    fn new(sh: &Shell, path: impl Into<PathBuf>) -> anyhow::Result<Patch> {
239        let path = path.into();
240        let contents = sh.read_file(&path)?;
241        Ok(Patch { path, original_contents: contents.clone(), contents })
242    }
243
244    fn replace(&mut self, from: &str, to: &str) -> &mut Patch {
245        assert!(self.contents.contains(from));
246        self.contents = self.contents.replace(from, to);
247        self
248    }
249
250    fn commit(&self, sh: &Shell) -> anyhow::Result<()> {
251        sh.write_file(&self.path, &self.contents)?;
252        Ok(())
253    }
254}
255
256impl Drop for Patch {
257    fn drop(&mut self) {
258        // FIXME: find a way to bring this back
259        let _ = &self.original_contents;
260        // write_file(&self.path, &self.original_contents).unwrap();
261    }
262}