uggo 0.9.5

CLI tool to query builds from u.gg, for League of Legends.
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#![deny(clippy::pedantic)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::struct_excessive_bools)]

#[macro_use]
extern crate prettytable;

use colored::Colorize;

#[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
use league_client_connector::LeagueClientConnector;

use anyhow::{anyhow, Result};
use prettytable::{format, Table};
use std::env::args_os;
use std::io;
use std::io::Write;
use std::process::exit;
use text_io::read;
use ugg_types::mappings::{self, Mode};

use crate::styling::format_ability_order;

#[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
use ugg_types::client_runepage::NewRunePage;

mod api;
#[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
mod client_api;

mod config;
mod styling;
mod util;

static DEFAULT_MODE: mappings::Mode = mappings::Mode::Normal;
static DEFAULT_ROLE: mappings::Role = mappings::Role::Automatic;
static DEFAULT_REGION: mappings::Region = mappings::Region::World;

const HELP_MESSAGE: &str = "\
CLI tool to query builds from u.gg, for League of Legends.

Usage: uggo [OPTIONS] [CHAMP]

Arguments:
  [CHAMP]
          The name of the champion you want to match. A best effort will be made to find the champ if it's only a partial query.

          If left blank, will open the interactive version of uggo.

Options:
  -m, --mode <MODE>
          [default: Normal]
          [possible values: normal, aram, one-for-all, urf, arurf]

  -r, --role <ROLE>
          [default: Automatic]
          [possible values: jungle, support, ad-carry, top, mid, none, automatic]

  -R, --region <REGION>
          [default: World]
          [possible values: na1, euw1, kr, eun1, br1, la1, la2, oc1, run, tr1, jp1, world]

  -h, --help
          Print help information (use `-h` for a summary)

  -V, --version
          Print version information
";

#[derive(Debug)]
struct Args {
    /// The game mode to look for data from. Can be one of: Normal, ARAM, URF, ARURF
    /// or OneForAll.
    mode: mappings::Mode,

    /// Can be specified to pull build data for a specific role. By default, this will
    /// not be necessary as the most popular role will be picked automatically. In ARAM,
    /// this setting is ignored. Can be one of Jungle, Support, ADCarry, Mid, Top, or
    /// Automatic.
    role: mappings::Role,

    /// The region to use to filter build results. By default, this uses all regions.
    /// Can be one of: NA1, EUW1, KR, EUN1, BR1, LA1, LA2, OC1, RU, TR1, JP1, World
    region: mappings::Region,

    /// The name of the champion you want to match. A best effort will be made
    /// to find the champ if it's only a partial query.
    ///
    /// If left blank, will open the interactive version of uggo.
    champ: Option<String>,
}

fn fetch(
    ugg: &api::UggApi,
    #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
    client: &Option<client_api::ClientAPI>,
    #[cfg(not(any(target_os = "windows", target_os = "macos", target_feature = "clippy")))] _client: Option<bool>,
    champ: &str,
    mode: mappings::Mode,
    role: mappings::Role,
    region: mappings::Region,
) {
    let query_champ = ugg.find_champ(champ);

    let formatted_champ_name = query_champ.name.as_str().green().bold();

    let mut query_message = vec![format!("Looking up info for {formatted_champ_name}")];
    if role != DEFAULT_ROLE {
        query_message.push(format!(", playing {}", role.to_string().blue().bold()));
    }
    if region != DEFAULT_REGION {
        query_message.push(format!(", in {}", region.to_string().red().bold()));
    }
    query_message.push("...".to_string());
    util::log_info(query_message.concat().as_str());

    let champ_overview = if let Ok(data) = ugg.get_stats(query_champ, role, region, mode) {
        *data
    } else {
        util::log_error(format!("Couldn't get required data for {formatted_champ_name}.").as_str());
        return;
    };

    let matchups = if mode == Mode::ARAM {
        Err(anyhow!("ARAM does not have matchup data."))
    } else {
        ugg.get_matchups(query_champ, role, region, mode)
    };

    let stats_message = vec![format!("Build for {formatted_champ_name}")];
    let true_length = 10 /* "Build for " */ + query_champ.name.len();
    let stats_message_str = stats_message.concat();
    println!(" {}", "-".repeat(true_length));
    println!(" {stats_message_str}");
    println!(" {}", "-".repeat(true_length));

    let champ_runes = util::group_runes(&champ_overview.runes.rune_ids, &ugg.runes);
    let mut rune_table = Table::new();
    rune_table.set_format(*format::consts::FORMAT_CLEAN);
    rune_table.add_row(row![
        styling::format_rune_group(champ_runes[0].0.as_str()),
        "",
        styling::format_rune_group(champ_runes[1].0.as_str()),
        ""
    ]);
    rune_table.add_row(row![
        &champ_runes[0].1[0].rune.name,
        styling::format_rune_position(champ_runes[0].1[0]),
        format!(
            "{} (Row {})",
            &champ_runes[1].1[0].rune.name, &champ_runes[1].1[0].slot
        ),
        styling::format_rune_position(champ_runes[1].1[0])
    ]);
    rune_table.add_row(row![
        &champ_runes[0].1[1].rune.name,
        styling::format_rune_position(champ_runes[0].1[1]),
        format!(
            "{} (Row {})",
            &champ_runes[1].1[1].rune.name, &champ_runes[1].1[1].slot
        ),
        styling::format_rune_position(champ_runes[1].1[1])
    ]);
    rune_table.add_row(row![
        &champ_runes[0].1[2].rune.name,
        styling::format_rune_position(champ_runes[0].1[2])
    ]);
    rune_table.add_row(row![
        &champ_runes[0].1[3].rune.name,
        styling::format_rune_position(champ_runes[0].1[3])
    ]);
    rune_table.printstd();

    println!();
    println!(" {}", "Shards:".magenta().bold());
    for shard in &util::process_shards(&champ_overview.shards.shard_ids) {
        println!(" {shard}");
    }

    println!();
    println!(
        " {} {}, {}",
        "Spells:".yellow().bold(),
        &ugg.summoner_spells[&champ_overview.summoner_spells.spell_ids[0]],
        &ugg.summoner_spells[&champ_overview.summoner_spells.spell_ids[1]]
    );

    println!();
    println!(" {}", "Ability Order:".bright_cyan().bold(),);
    format_ability_order(&champ_overview.abilities.ability_order).printstd();

    let mut item_table = Table::new();
    item_table.set_format(*format::consts::FORMAT_CLEAN);
    item_table.add_row(row![
        r->"Starting:".green(),
        util::process_items(&champ_overview.starting_items.item_ids, &ugg.items)
    ]);
    item_table.add_row(row![
        r->"Core:".green(),
        util::process_items(&champ_overview.core_items.item_ids, &ugg.items)
    ]);
    item_table.add_row(row![
        r->"4th:".green(),
        util::process_items(&champ_overview.item_4_options.iter().map(|x| x.id).collect::<Vec<i64>>(), &ugg.items)
    ]);
    item_table.add_row(row![
        r->"5th:".green(),
        util::process_items(&champ_overview.item_5_options.iter().map(|x| x.id).collect::<Vec<i64>>(), &ugg.items)
    ]);
    item_table.add_row(row![
        r->"6th:".green(),
        util::process_items(&champ_overview.item_6_options.iter().map(|x| x.id).collect::<Vec<i64>>(), &ugg.items)
    ]);
    println!();
    item_table.printstd();

    if let Ok(safe_matchups) = matchups {
        let mut matchup_table = Table::new();
        matchup_table.set_format(*format::consts::FORMAT_CLEAN);
        matchup_table.add_row(row![
            r->"Best Matchups:".cyan().bold(),
            safe_matchups
                .best_matchups
                .into_iter()
                .map(|m| util::find_champ_by_key(m.champion_id, &ugg.champ_data)
                    .unwrap()
                    .name
                    .as_str())
                .collect::<Vec<&str>>()
                .join(", ")
        ]);
        matchup_table.add_row(row![
            r->"Worst Matchups:".red().bold(),
            safe_matchups
                .worst_matchups
                .into_iter()
                .map(|m| util::find_champ_by_key(m.champion_id, &ugg.champ_data)
                    .unwrap()
                    .name
                    .as_str())
                .collect::<Vec<&str>>()
                .join(", ")
        ]);
        println!();
        matchup_table.printstd();
    }

    if champ_overview.low_sample_size {
        println!();
        println!(
            " {} Data has a low sample size for this combination!",
            "Warning:".yellow().bold()
        );
    }

    #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
    match client {
        Some(ref api) => match api.get_current_rune_page() {
            Some(data) => {
                let (primary_style_id, sub_style_id, selected_perk_ids) =
                    util::generate_perk_array(&champ_runes, &champ_overview.shards.shard_ids);
                api.update_rune_page(
                    &data.id,
                    &NewRunePage {
                        name: match mode {
                            mappings::Mode::ARAM => {
                                format!("uggo: {}, ARAM", &query_champ.name)
                            }
                            mappings::Mode::URF => format!("uggo: {}, URF", &query_champ.name),
                            _ => format!("uggo: {}, Normal", &query_champ.name),
                        },
                        primary_style_id,
                        sub_style_id,
                        selected_perk_ids,
                    },
                );
            }
            _ => (),
        },
        None => (),
    }
}

fn main() -> Result<()> {
    let ugg = api::UggApi::new()?;
    let mut mode = mappings::Mode::Normal;

    #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
    let client_lockfile = LeagueClientConnector::parse_lockfile().ok();

    #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
    let mut clientapi: Option<client_api::ClientAPI> = None;

    #[cfg(all(
        debug_assertions,
        any(target_os = "windows", target_os = "macos", target_feature = "clippy")
    ))]
    if !client_lockfile.as_ref().is_none() {
        let lockfile = client_lockfile.clone().unwrap();
        util::log_info(&format!(
            "- Found client running at https://127.0.0.1:{}/",
            lockfile.port
        ));
        clientapi = Some(client_api::ClientAPI::new(lockfile));
    }

    #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
    if !client_lockfile.as_ref().is_none() {
        clientapi = Some(client_api::ClientAPI::new(client_lockfile.clone().unwrap()));
    }

    #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
    match clientapi {
        Some(ref api) => match api.get_summoner_info() {
            Some(summoner) => {
                #[cfg(debug_assertions)]
                util::log_info(&format!(
                    "- Found summoner {} (id: {})",
                    summoner.display_name, summoner.summoner_id
                ));
            }
            None => (),
        },
        None => (),
    }

    let mut raw_args: Vec<_> = args_os().collect();
    raw_args.remove(0);
    let mut args = pico_args::Arguments::from_vec(raw_args);

    if args.contains(["-h", "--help"]) {
        print!("{HELP_MESSAGE}");
        exit(0);
    }

    if args.contains(["-V", "--version"]) {
        println!("uggo v{}", env!("CARGO_PKG_VERSION"));
        exit(0);
    }

    let parsed_args = Args {
        champ: args.free_from_str().ok(),
        mode: args
            .value_from_str::<[&str; 2], mappings::Mode>(["-m", "--mode"])
            .map_or(DEFAULT_MODE, |m| m),
        role: args
            .value_from_str::<[&str; 2], mappings::Role>(["-r", "--role"])
            .map_or(DEFAULT_ROLE, |r| r),
        region: args
            .value_from_str::<[&str; 2], mappings::Region>(["-R", "--region"])
            .map_or(DEFAULT_REGION, |r| r),
    };

    if let Some(champ_name) = parsed_args.champ {
        #[cfg(not(any(target_os = "windows", target_os = "macos", target_feature = "clippy")))]
        fetch(
            &ugg,
            None,
            &champ_name,
            parsed_args.mode,
            parsed_args.role,
            parsed_args.region,
        );

        #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
        fetch(
            &ugg,
            &clientapi,
            &champ_name,
            parsed_args.mode,
            parsed_args.role,
            parsed_args.region,
        );
        return Ok(());
    }

    loop {
        print!("query> ");
        io::stdout().flush().unwrap();
        let user_input: String = read!("{}\n");
        let clean_user_input = user_input.trim();
        let user_input_split = clean_user_input
            .split(',')
            .map(str::trim)
            .collect::<Vec<&str>>();

        if clean_user_input == "modes" {
            util::log_info("Available modes:");
            mappings::Mode::all()
                .iter()
                .for_each(|m| util::log_info(format!("- {m:?}").as_str()));
            continue;
        }

        if clean_user_input.starts_with("mode") {
            let mode_to_set = clean_user_input.split(' ').collect::<Vec<&str>>();
            if mode_to_set.len() > 1 {
                mode = mappings::Mode::from(mode_to_set[1]);
                util::log_info(format!("Switching mode to {mode:?}...").as_str());
                continue;
            }
            util::log_info(format!("Current mode: {mode:?}").as_str());
            continue;
        }

        let mut query_champ_name = "";
        let mut query_role = DEFAULT_ROLE;
        let mut query_region = DEFAULT_REGION;

        if user_input_split.is_empty()
            || user_input_split.len() > 3
            || user_input_split[0].is_empty()
        {
            util::log_info("This doesn't look like a valid query.");
            util::log_info("Query format is <champion>[,<role>][,<region>]");
            continue;
        }
        if !user_input_split.is_empty() {
            query_champ_name = user_input_split[0];
        }
        if user_input_split.len() >= 2 {
            let try_role = mappings::get_role(user_input_split[1]);
            if try_role == query_role {
                query_region = mappings::get_region(user_input_split[1]);
            } else {
                query_role = try_role;
            }
        }
        if user_input_split.len() == 3 {
            query_role = mappings::get_role(user_input_split[1]);
            query_region = mappings::get_region(user_input_split[2]);
        }

        #[cfg(not(any(target_os = "windows", target_os = "macos", target_feature = "clippy")))]
        fetch(&ugg, None, query_champ_name, mode, query_role, query_region);

        #[cfg(any(target_os = "windows", target_os = "macos", target_feature = "clippy"))]
        fetch(
            &ugg,
            &clientapi,
            query_champ_name,
            mode,
            query_role,
            query_region,
        );

        println!();
    }
}