canvas_grading/
lib.rs

1use std::str::FromStr;
2
3use anyhow::{Context, Result};
4use clap::{Parser, Subcommand};
5use clap_complete::Shell;
6use reqwest::Client;
7use serde::{Deserialize, Serialize};
8use tracing::info;
9
10mod config;
11mod file;
12mod submission;
13
14pub use config::Config;
15pub use file::FileSubmission;
16pub use submission::Submission;
17
18/// A struct representing an access token for Canvas. Hides its value from Debug.
19#[derive(Serialize, Deserialize, Clone)]
20pub struct AccessToken(String);
21
22impl std::fmt::Debug for AccessToken {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "AccessToken")
25    }
26}
27
28impl AccessToken {
29    pub fn secret(&self) -> &str {
30        &self.0
31    }
32}
33
34#[derive(Parser, Clone, Debug)]
35#[command(version, about, long_about = None)]
36pub struct CLI {
37    /// Override the Canvas access token from config.
38    /// Either this or the option in config MUST BE SET
39    #[arg(long)]
40    pub access_token: Option<String>,
41
42    /// Override the course id from config.
43    /// Either this or the option in config MUST BE SET
44    #[arg(long, short)]
45    pub course_id: Option<u64>,
46
47    /// Override the base URL for Canvas from config.
48    /// Either this or the option in config MUST BE SET
49    #[arg(long, short)]
50    pub base_url: Option<String>,
51
52    /// Generate shell completion
53    #[arg(long)]
54    generate: Option<Shell>,
55
56    #[command(subcommand)]
57    pub command: Command,
58
59    /// Assignment ID in Canvas
60    pub assignment_id: u64,
61}
62
63#[derive(Subcommand, Clone, Debug)]
64pub enum Command {
65    /// Download ungraded submissions and print the paths to standard output
66    Submissions,
67    /// Upload grades and comments from file
68    Grade,
69    /// Count the number of submissions meeting a requirement
70    #[command(subcommand)]
71    Count(CountOptions),
72}
73
74#[derive(Subcommand, Clone, Debug)]
75pub enum CountOptions {
76    Unsubmitted,
77    Submitted,
78    Graded,
79}
80
81#[derive(Debug)]
82pub struct Grade {
83    pub user_id: u64,
84    pub grade: f32,
85}
86
87impl FromStr for Grade {
88    type Err = anyhow::Error;
89
90    fn from_str(s: &str) -> Result<Self, Self::Err> {
91        let mut parts = s.split(": ");
92        let user_id = parts
93            .next()
94            .context("Unable to parse user id from stdin.")?;
95        let grade = parts.next().context("Unable to parse grade from stdin.")?;
96
97        Ok(Self {
98            user_id: user_id.parse().context("Unable to parse user id to u64")?,
99            grade: grade.parse().context("Unable to parse grade to f32")?,
100        })
101    }
102}
103
104#[derive(Debug)]
105pub struct Comment {
106    pub user_id: u64,
107    pub comment: String,
108}
109
110impl FromStr for Comment {
111    type Err = anyhow::Error;
112
113    fn from_str(s: &str) -> Result<Self, Self::Err> {
114        let (user_id, comment) = s
115            .split_once(": ")
116            .context("Unable to parse comment line.")?;
117
118        Ok(Self {
119            user_id: user_id.parse().context("Unable to parse user id to u64")?,
120            comment: comment.to_string(),
121        })
122    }
123}
124
125pub fn create_client(auth_token: AccessToken) -> Result<Client> {
126    info!("Building application reqwest client...");
127    info!("Setting auth header...");
128    let mut auth_bearer: reqwest::header::HeaderValue = ("Bearer ".to_owned()
129        + auth_token.secret())
130    .try_into()
131    .unwrap();
132    auth_bearer.set_sensitive(true);
133    info!("Auth header set!");
134
135    let mut headers = reqwest::header::HeaderMap::new();
136    headers.insert(reqwest::header::AUTHORIZATION, auth_bearer);
137    headers.insert("per_page", 100.into());
138
139    Ok(reqwest::ClientBuilder::new()
140        .default_headers(headers)
141        .build()?)
142}