]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/xtask/src/dist.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / src / tools / rust-analyzer / xtask / src / dist.rs
1 use std::{
2     env,
3     fs::File,
4     io::{self, BufWriter},
5     path::{Path, PathBuf},
6 };
7
8 use flate2::{write::GzEncoder, Compression};
9 use xshell::{cmd, Shell};
10 use zip::{write::FileOptions, DateTime, ZipWriter};
11
12 use crate::{date_iso, flags, project_root};
13
14 const VERSION_STABLE: &str = "0.3";
15 const VERSION_NIGHTLY: &str = "0.4";
16 const VERSION_DEV: &str = "0.5"; // keep this one in sync with `package.json`
17
18 impl flags::Dist {
19     pub(crate) fn run(self, sh: &Shell) -> anyhow::Result<()> {
20         let stable = sh.var("GITHUB_REF").unwrap_or_default().as_str() == "refs/heads/release";
21
22         let project_root = project_root();
23         let target = Target::get(&project_root);
24         let dist = project_root.join("dist");
25         sh.remove_path(&dist)?;
26         sh.create_dir(&dist)?;
27
28         if let Some(patch_version) = self.client_patch_version {
29             let version = if stable {
30                 format!("{VERSION_STABLE}.{patch_version}")
31             } else {
32                 // A hack to make VS Code prefer nightly over stable.
33                 format!("{VERSION_NIGHTLY}.{patch_version}")
34             };
35             dist_server(sh, &format!("{version}-standalone"), &target)?;
36             let release_tag = if stable { date_iso(sh)? } else { "nightly".to_string() };
37             dist_client(sh, &version, &release_tag, &target)?;
38         } else {
39             dist_server(sh, "0.0.0-standalone", &target)?;
40         }
41         Ok(())
42     }
43 }
44
45 fn dist_client(
46     sh: &Shell,
47     version: &str,
48     release_tag: &str,
49     target: &Target,
50 ) -> anyhow::Result<()> {
51     let bundle_path = Path::new("editors").join("code").join("server");
52     sh.create_dir(&bundle_path)?;
53     sh.copy_file(&target.server_path, &bundle_path)?;
54     if let Some(symbols_path) = &target.symbols_path {
55         sh.copy_file(symbols_path, &bundle_path)?;
56     }
57
58     let _d = sh.push_dir("./editors/code");
59
60     let mut patch = Patch::new(sh, "./package.json")?;
61     patch
62         .replace(
63             &format!(r#""version": "{VERSION_DEV}.0-dev""#),
64             &format!(r#""version": "{version}""#),
65         )
66         .replace(r#""releaseTag": null"#, &format!(r#""releaseTag": "{release_tag}""#))
67         .replace(r#""$generated-start": {},"#, "")
68         .replace(",\n                \"$generated-end\": {}", "")
69         .replace(r#""enabledApiProposals": [],"#, r#""#);
70     patch.commit(sh)?;
71
72     Ok(())
73 }
74
75 fn dist_server(sh: &Shell, release: &str, target: &Target) -> anyhow::Result<()> {
76     let _e = sh.push_env("CFG_RELEASE", release);
77     let _e = sh.push_env("CARGO_PROFILE_RELEASE_LTO", "thin");
78
79     // Uncomment to enable debug info for releases. Note that:
80     //   * debug info is split on windows and macs, so it does nothing for those platforms,
81     //   * on Linux, this blows up the binary size from 8MB to 43MB, which is unreasonable.
82     // let _e = sh.push_env("CARGO_PROFILE_RELEASE_DEBUG", "1");
83
84     if target.name.contains("-linux-") {
85         env::set_var("CC", "clang");
86     }
87
88     let target_name = &target.name;
89     cmd!(sh, "cargo build --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --target {target_name} --release").run()?;
90
91     let dst = Path::new("dist").join(&target.artifact_name);
92     gzip(&target.server_path, &dst.with_extension("gz"))?;
93     if target_name.contains("-windows-") {
94         zip(&target.server_path, target.symbols_path.as_ref(), &dst.with_extension("zip"))?;
95     }
96
97     Ok(())
98 }
99
100 fn gzip(src_path: &Path, dest_path: &Path) -> anyhow::Result<()> {
101     let mut encoder = GzEncoder::new(File::create(dest_path)?, Compression::best());
102     let mut input = io::BufReader::new(File::open(src_path)?);
103     io::copy(&mut input, &mut encoder)?;
104     encoder.finish()?;
105     Ok(())
106 }
107
108 fn zip(src_path: &Path, symbols_path: Option<&PathBuf>, dest_path: &Path) -> anyhow::Result<()> {
109     let file = File::create(dest_path)?;
110     let mut writer = ZipWriter::new(BufWriter::new(file));
111     writer.start_file(
112         src_path.file_name().unwrap().to_str().unwrap(),
113         FileOptions::default()
114             .last_modified_time(
115                 DateTime::from_time(std::fs::metadata(src_path)?.modified()?.into()).unwrap(),
116             )
117             .unix_permissions(0o755)
118             .compression_method(zip::CompressionMethod::Deflated)
119             .compression_level(Some(9)),
120     )?;
121     let mut input = io::BufReader::new(File::open(src_path)?);
122     io::copy(&mut input, &mut writer)?;
123     if let Some(symbols_path) = symbols_path {
124         writer.start_file(
125             symbols_path.file_name().unwrap().to_str().unwrap(),
126             FileOptions::default()
127                 .last_modified_time(
128                     DateTime::from_time(std::fs::metadata(src_path)?.modified()?.into()).unwrap(),
129                 )
130                 .compression_method(zip::CompressionMethod::Deflated)
131                 .compression_level(Some(9)),
132         )?;
133         let mut input = io::BufReader::new(File::open(symbols_path)?);
134         io::copy(&mut input, &mut writer)?;
135     }
136     writer.finish()?;
137     Ok(())
138 }
139
140 struct Target {
141     name: String,
142     server_path: PathBuf,
143     symbols_path: Option<PathBuf>,
144     artifact_name: String,
145 }
146
147 impl Target {
148     fn get(project_root: &Path) -> Self {
149         let name = match env::var("RA_TARGET") {
150             Ok(target) => target,
151             _ => {
152                 if cfg!(target_os = "linux") {
153                     "x86_64-unknown-linux-gnu".to_string()
154                 } else if cfg!(target_os = "windows") {
155                     "x86_64-pc-windows-msvc".to_string()
156                 } else if cfg!(target_os = "macos") {
157                     "x86_64-apple-darwin".to_string()
158                 } else {
159                     panic!("Unsupported OS, maybe try setting RA_TARGET")
160                 }
161             }
162         };
163         let out_path = project_root.join("target").join(&name).join("release");
164         let (exe_suffix, symbols_path) = if name.contains("-windows-") {
165             (".exe".into(), Some(out_path.join("rust_analyzer.pdb")))
166         } else {
167             (String::new(), None)
168         };
169         let server_path = out_path.join(format!("rust-analyzer{exe_suffix}"));
170         let artifact_name = format!("rust-analyzer-{name}{exe_suffix}");
171         Self { name, server_path, symbols_path, artifact_name }
172     }
173 }
174
175 struct Patch {
176     path: PathBuf,
177     original_contents: String,
178     contents: String,
179 }
180
181 impl Patch {
182     fn new(sh: &Shell, path: impl Into<PathBuf>) -> anyhow::Result<Patch> {
183         let path = path.into();
184         let contents = sh.read_file(&path)?;
185         Ok(Patch { path, original_contents: contents.clone(), contents })
186     }
187
188     fn replace(&mut self, from: &str, to: &str) -> &mut Patch {
189         assert!(self.contents.contains(from));
190         self.contents = self.contents.replace(from, to);
191         self
192     }
193
194     fn commit(&self, sh: &Shell) -> anyhow::Result<()> {
195         sh.write_file(&self.path, &self.contents)?;
196         Ok(())
197     }
198 }
199
200 impl Drop for Patch {
201     fn drop(&mut self) {
202         // FIXME: find a way to bring this back
203         let _ = &self.original_contents;
204         // write_file(&self.path, &self.original_contents).unwrap();
205     }
206 }