turbocommit 0.8.4

A CLI tool to create commit messages with gpt-3.5-turbo
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
use colored::Colorize;
use config::Config;
use crossterm::{
    cursor::{self, MoveTo, MoveToColumn, MoveToPreviousLine},
    execute,
    style::{Color, Print, ResetColor, SetForegroundColor},
    terminal::{self, Clear, ClearType},
};
use futures::stream::StreamExt;
use inquire::{validator::Validation, Confirm, CustomUserError, MultiSelect};
use openai::Message;

use reqwest_eventsource::{Event, EventSource};
use std::time::Duration;
use std::{env, process};
use unicode_segmentation::UnicodeSegmentation;

mod cli;
mod config;
mod git;
mod openai;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::load();
    match config.save() {
        Ok(_) => (),
        Err(err) => {
            println!("{}", format!("Unable to write to config: {err}").red());
            process::exit(1);
        }
    }
    let options = cli::Options::new(env::args(), &config);

    let Ok(api_key) = env::var("OPENAI_API_KEY") else {
        println!("{} {}", "OPENAI_API_KEY not set.".red(), "Refer to step 3 here: https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety".bright_black());
        process::exit(1);
    };

    let loading_git_animation = tokio::spawn(async {
        let emoji_support =
            terminal_supports_emoji::supports_emoji(terminal_supports_emoji::Stream::Stdout);
        let frames = if emoji_support {
            vec![
                "🕛", "🕐", "🕑", "🕒", "🕓", "🕔", "🕕", "🕖", "🕗", "🕘", "🕙", "🕚",
            ]
        } else {
            vec!["/", "-", "\\", "|"]
        };
        let mut current_frame = 0;
        let mut stdout = std::io::stdout();
        loop {
            current_frame = (current_frame + 1) % frames.len();
            match execute!(
                stdout,
                Clear(ClearType::CurrentLine),
                MoveToColumn(0),
                SetForegroundColor(Color::Yellow),
                Print("Extracting Information ".bright_black()),
                Print(frames[current_frame]),
                ResetColor
            ) {
                Ok(_) => (),
                Err(_) => {
                    break;
                }
            }
            tokio::time::sleep(Duration::from_millis(150)).await;
        }
    });

    let repo = git::get_repo()?;
    let staged_files = git::staged_files(&repo)?;
    let full_diff = git::diff(&repo, &staged_files)?;

    if full_diff.trim().is_empty() {
        loading_git_animation.abort();
        execute!(
            std::io::stdout(),
            Clear(ClearType::CurrentLine),
            MoveToColumn(0),
        )?;
        println!(
            "{} {}",
            "No staged files.".red(),
            "Please stage the files you want to commit.".bright_black()
        );
        check_version().await;
        process::exit(0);
    }

    let system_len = openai::count_token(&config.system_msg).unwrap_or(0);
    let extra_len = openai::count_token(&options.msg).unwrap_or(0);

    let mut diff = full_diff;
    let mut diff_tokens = match openai::count_token(&diff) {
        Ok(tokens) => tokens,
        Err(e) => {
            println!("{}", format!("{e}").red());
            process::exit(1);
        }
    };

    loading_git_animation.abort();
    execute!(
        std::io::stdout(),
        Clear(ClearType::CurrentLine),
        MoveToColumn(0),
    )?;
    while system_len + extra_len + diff_tokens > options.model.context_size() {
        println!(
            "{} {}",
            "The request is too long!".red(),
            format!(
                "The request is ~{} tokens long, while the maximum is 4096.",
                system_len + extra_len + diff_tokens
            )
            .bright_black()
        );
        let selected_files = match MultiSelect::new(
            "Select the files you want to include in the diff:",
            staged_files.clone(),
        )
        .prompt()
        {
            Ok(selected_files) => selected_files,
            Err(e) => {
                println!("{}", format!("{e}").red());
                process::exit(1);
            }
        };
        diff = match git::diff(&repo, &selected_files) {
            Ok(diff) => diff,
            Err(e) => {
                println!("{}", format!("{e}").red());
                process::exit(1);
            }
        };
        diff_tokens = match openai::count_token(&diff) {
            Ok(tokens) => tokens,
            Err(e) => {
                println!("{}", format!("{e}").red());
                process::exit(1);
            }
        };
    }

    if options.dry_run {
        println!("This will use ~{} prompt tokens, costing you ~${}.\nEach 1K completion tokens will cost you ~${}",
            format!("{}", system_len + extra_len + diff_tokens).purple(),
            format!("{:0.5}", options.model.cost(system_len + extra_len + diff_tokens, 0)).purple(),
            format!("{:0.5}", options.model.cost(0, 1000)).purple());
        check_version().await;
        process::exit(0);
    }

    let prompt_tokens = system_len + extra_len + diff_tokens;

    let mut messages = vec![Message::system(config.system_msg), Message::user(diff)];

    if !options.msg.is_empty() {
        messages.push(Message::user(options.msg));
    }

    let req = openai::Request::new(
        options.model.clone().to_string(),
        messages,
        options.n,
        options.t,
        options.f,
    );

    let json = match serde_json::to_string(&req) {
        Ok(json) => json,
        Err(e) => {
            println!("{e}");
            process::exit(1);
        }
    };

    let request_builder = reqwest::Client::new()
        .post("https://api.openai.com/v1/chat/completions")
        .header("Content-Type", "application/json")
        .bearer_auth(api_key)
        .body(json);

    let loading_ai_animation = tokio::spawn(async {
        let emoji_support =
            terminal_supports_emoji::supports_emoji(terminal_supports_emoji::Stream::Stdout);
        let frames = if emoji_support {
            vec![
                "🕛", "🕐", "🕑", "🕒", "🕓", "🕔", "🕕", "🕖", "🕗", "🕘", "🕙", "🕚",
            ]
        } else {
            vec!["/", "-", "\\", "|"]
        };
        let mut current_frame = 0;
        let mut stdout = std::io::stdout();
        loop {
            current_frame = (current_frame + 1) % frames.len();
            match execute!(
                stdout,
                Clear(ClearType::CurrentLine),
                MoveToColumn(0),
                SetForegroundColor(Color::Yellow),
                Print("Asking AI ".bright_black()),
                Print(frames[current_frame]),
                ResetColor
            ) {
                Ok(_) => {}
                Err(_) => {
                    break;
                }
            }
            tokio::time::sleep(Duration::from_millis(150)).await;
        }
    });

    let mut choices = vec![String::from(""); options.n as usize];

    let term_width = terminal::size()?.0 as usize;
    let term_height = terminal::size()?.1 as usize;

    let mut stdout = std::io::stdout();

    let mut es = EventSource::new(request_builder)?;
    let mut lines_to_move_up = 0;
    let mut response_tokens = 0;
    while let Some(event) = es.next().await {
        if !loading_ai_animation.is_finished() {
            loading_ai_animation.abort();
            execute!(
                std::io::stdout(),
                Clear(ClearType::CurrentLine),
                MoveToColumn(0),
            )?;
            print!("\n\n")
        }

        execute!(
            stdout,
            cursor::SavePosition,
            MoveToPreviousLine(lines_to_move_up),
        )?;
        lines_to_move_up = 0;
        match event {
            Ok(Event::Message(message)) => {
                if message.data == "[DONE]" {
                    break;
                }
                execute!(stdout, Clear(ClearType::FromCursorDown),)?;
                let resp = serde_json::from_str::<openai::Response>(&message.data)
                    .map_or_else(|_| openai::Response::default(), |r| r);
                response_tokens += 1;
                for choice in resp.choices {
                    if let Some(content) = choice.delta.content {
                        choices[choice.index as usize].push_str(&content);
                    }
                }
                for (i, choice) in choices.iter().enumerate() {
                    let outp = format!(
                        "{}{}\n{}\n",
                        if i == 0 {
                            format!(
                                "This used {} tokens costing you about {}\n",
                                format!("{}", response_tokens + prompt_tokens).purple(),
                                format!(
                                    "~${:0.4}",
                                    options.model.cost(prompt_tokens, response_tokens)
                                )
                                .purple()
                            )
                            .bright_black()
                        } else {
                            "".bright_black()
                        },
                        format!("[{}]====================", format!("{i}").purple()).bright_black(),
                        choice,
                    );
                    print!("{outp}");
                    lines_to_move_up += count_lines(&outp, term_width) - 1;
                }
            }
            Err(e) => {
                println!("{e}");
                process::exit(1);
            }
            _ => {}
        }
    }

    execute!(
        stdout,
        // MoveTo(0, term_height as u16),
        cursor::RestorePosition,
        Print(format!(
            "{}\n",
            "=======================".bright_black()
        )),
    )?;

    if choices.len() == 1 {
        let answer = match Confirm::new("Do you want to commit with this message? ")
            .with_default(true)
            .prompt()
        {
            Ok(answer) => answer,
            Err(e) => {
                println!("{e}");
                process::exit(1);
            }
        };
        if answer {
            match git::commit(choices[0].clone()) {
                Ok(_) => {}
                Err(e) => {
                    println!("{e}");
                    process::exit(1);
                }
            };
            println!("{} 🎉", "Commit successful!".purple());
        }
        check_version().await;
        process::exit(0);
    }
    let max_index = choices.len();
    let commit_index = match inquire::CustomType::<usize>::new(&format!(
        "Which commit message do you want to use? {}",
        "<ESC> to cancel".bright_black()
    ))
    .with_validator(move |i: &usize| {
        if *i >= max_index {
            Err(CustomUserError::from("Invalid index"))
        } else {
            Ok(Validation::Valid)
        }
    })
    .prompt()
    {
        Ok(i) => i,
        Err(e) => {
            println!("{e}");
            process::exit(1);
        }
    };
    let commit_msg = choices[commit_index].clone();
    match git::commit(commit_msg) {
        Ok(_) => {}
        Err(e) => {
            println!("{e}");
            process::exit(1);
        }
    };
    println!("{} 🎉", "Commit successful!".purple());
    check_version().await;

    Ok(())
}

async fn check_version() {
    let client = match crates_io_api::AsyncClient::new(
        "turbocommit lateste version checker",
        Duration::from_millis(1000),
    ) {
        Ok(client) => client,
        Err(_) => {
            return;
        }
    };
    let turbo = match client.get_crate("turbocommit").await {
        Ok(turbo) => turbo,
        Err(_) => {
            return;
        }
    };
    let newest_version = turbo.versions[0].num.clone();
    let current_version = env!("CARGO_PKG_VERSION");

    if current_version != newest_version {
        println!(
            "\n{} {}",
            "New version available!".yellow(),
            format!("v{}", newest_version).purple()
        );
        println!(
            "To update, run\n{}",
            "cargo install --force turbocommit".purple()
        );
    }
}

#[must_use]
pub fn count_lines(text: &str, max_width: usize) -> u16 {
    if text.is_empty() {
        return 0;
    }
    let mut line_count = 0;
    let mut current_line_width = 0;
    for cluster in UnicodeSegmentation::graphemes(text, true) {
        match cluster {
            "\r" | "\u{FEFF}" => {}
            "\n" => {
                line_count += 1;
                current_line_width = 0;
            }
            _ => {
                current_line_width += 1;
                if current_line_width > max_width {
                    line_count += 1;
                    current_line_width = cluster.chars().count();
                }
            }
        }
    }

    line_count + 1
}