@@ -19,9 +19,7 @@ use url::Url;
19
19
use crate :: error:: { RedirectError , ToolError } ;
20
20
21
21
const REDIRECT_FILE_HEADER : & str = r#"# DO NOT EDIT THIS FILE MANUALLY.
22
- # Use the CLI instead::
23
- #
24
- # rari content add-redirect <fromURL> <toURL>
22
+ # Use the CLI instead.
25
23
#
26
24
# FROM-URL TO-URL
27
25
"# ;
@@ -242,6 +240,57 @@ pub fn add_redirects(locale: Locale, update_pairs: &[(String, String)]) -> Resul
242
240
Ok ( ( ) )
243
241
}
244
242
243
+ /// Optimizes redirect rules based on all suported locales.
244
+ ///
245
+ /// It loads all redirects into a singel structure and runs the short_cuts algorithm on it.
246
+ /// The goal is to optimize redirects across locale boundaries.
247
+ ///
248
+ /// This function overwrites all redirect files.
249
+ ///
250
+ /// # Returns
251
+ ///
252
+ /// - `Ok(())` if all operations complete successfully.
253
+ /// - `Err(ToolError)` if any step fails, such as:
254
+ /// - Invalid locale strings that cannot be parsed.
255
+ /// - I/O errors during file reading or writing.
256
+ /// - Errors from the `short_cuts` processing function.
257
+ pub fn fix_redirects ( ) -> Result < ( ) , ToolError > {
258
+ let locales = Locale :: for_generic_and_spas ( ) ;
259
+ let mut pairs = HashMap :: new ( ) ;
260
+ for locale in locales {
261
+ let path = redirects_path ( * locale) ?;
262
+ read_redirects_raw ( & path, & mut pairs) ?;
263
+ }
264
+ let clean_pairs: HashMap < String , String > = short_cuts ( & pairs) ?. into_iter ( ) . collect ( ) ;
265
+
266
+ // Split the clean pairs into their respective locales
267
+ let locale_pairs = clean_pairs. into_iter ( ) . try_fold (
268
+ HashMap :: < Locale , HashMap < String , String > > :: new ( ) ,
269
+ |mut acc, ( from, to) | -> Result < HashMap < Locale , HashMap < String , String > > , ToolError > {
270
+ // Extract the locale string from the 'from' path
271
+ let locale_str = from. split ( '/' ) . nth ( 1 ) . unwrap_or_default ( ) ;
272
+
273
+ // Parse the locale string into a Locale enum
274
+ let locale = Locale :: from_str ( locale_str) . map_err ( |_| {
275
+ ToolError :: InvalidLocale ( Cow :: Owned ( format ! (
276
+ "Cannot detect a valid locale for '{}'. Search for a '{}\t {}' pair in all _redirects.txt files to locate the problem." ,
277
+ from, from, to
278
+ ) ) )
279
+ } ) ?;
280
+ let locale_map = acc. entry ( locale) . or_default ( ) ;
281
+ locale_map. insert ( from, to) ;
282
+ Ok ( acc)
283
+ } ,
284
+ ) ?;
285
+
286
+ // Write the updated maps back to their redirects files
287
+ for ( locale, pairs) in & locale_pairs {
288
+ let path = redirects_path ( * locale) ?;
289
+ write_redirects ( & path, pairs) ?;
290
+ }
291
+ Ok ( ( ) )
292
+ }
293
+
245
294
/// Gets the path to the redirects file for a specific locale.
246
295
pub ( crate ) fn redirects_path ( locale : Locale ) -> Result < PathBuf , ToolError > {
247
296
let root = root_for_locale ( locale) ?;
0 commit comments