Skip to content

Commit

Permalink
Merge pull request #11 from phip1611/summary
Browse files Browse the repository at this point in the history
cli: refactor data-access layer + code cleanup
  • Loading branch information
phip1611 authored Sep 3, 2024
2 parents d815206 + 43d312f commit d1c6ed3
Show file tree
Hide file tree
Showing 9 changed files with 601 additions and 357 deletions.
28 changes: 14 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 9 additions & 14 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

inputs = {
crane.url = "github:ipetkov/crane/master";
crane.inputs.nixpkgs.follows = "nixpkgs";
flake-parts.url = "github:hercules-ci/flake-parts";
flake-parts.inputs.nixpkgs-lib.follows = "nixpkgs";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
Expand Down Expand Up @@ -76,6 +75,10 @@
devShells = {
default = pkgs.mkShell {
inputsFrom = [ self'.packages.default ];
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [
pkgs.openssl
];
};
};
formatter = pkgs.nixpkgs-fmt;
Expand Down
100 changes: 100 additions & 0 deletions src/cfg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
MIT License
Copyright (c) 2024 Philipp Schuster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

//! Module for obtaining the effective configuration, based on the configuration
//! file and CLI parameters.
//!
//! [`get_cfg`] is the entry point.
use crate::cli::{CfgFile, CliArgs};
use crate::{cli, print_warning};
use clap::Parser;
use serde::de::DeserializeOwned;
use std::error::Error;
use std::io::ErrorKind;
use std::path::PathBuf;

/// Returns the path of the config file with respect to the current OS.
fn config_file_path() -> Result<PathBuf, Box<dyn Error>> {
#[cfg(target_family = "unix")]
let config_os_dir = {
// First look for XDG_CONFIG_HOME, then fall back to HOME
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
let home = std::env::var("XDG_CONFIG_HOME").unwrap_or(std::env::var("HOME")?);
PathBuf::from(home).join(".config")
};
#[cfg(target_family = "windows")]
let config_os_dir = PathBuf::from(std::env::var("LOCALAPPDATA")?);

let config_dir = config_os_dir.join("gitlab-timelogs");
Ok(config_dir.join("config.toml"))
}

/// Reads the config file and parses it from TOML.
/// On UNIX, it uses `
fn read_config_file<T: DeserializeOwned>() -> Result<T, Box<dyn Error>> {
let config_file = config_file_path()?;
let content = match std::fs::read_to_string(&config_file) {
Ok(c) => c,
Err(e) => {
match e.kind() {
ErrorKind::NotFound => {}
_ => print_warning(
&format!(
"Failed to read config file at {}: {e}",
config_file.display()
),
0,
),
}

// Treat failure to read a config file as the empty config file.
String::new()
}
};

Ok(toml::from_str(&content)?)
}

/// Parses the command line options but first, reads the config file. If certain
/// command line options are not present, they are taken from the config file.
///
/// This is a workaround that clap has no built-in support for a config file
/// that serves as source for command line options by itself. The focus is
/// also on the natural error reporting by clap.
pub fn get_cfg() -> Result<CliArgs, Box<dyn Error>> {
let config_content = read_config_file::<CfgFile>()?;
let config_args: Vec<(String, String)> = config_content.to_cli_args();
let mut all_args = std::env::args().collect::<Vec<_>>();

// Push config options as arguments, before parsing them in clap.
for (opt_name, opt_value) in config_args {
if !all_args.contains(&opt_name) {
all_args.push(opt_name);
all_args.push(opt_value);
}
}

Ok(cli::CliArgs::parse_from(all_args))
}
142 changes: 142 additions & 0 deletions src/fetch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
MIT License
Copyright (c) 2024 Philipp Schuster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

//! Functionality to fetch data from the GitLab API.
//!
//! [`fetch_results`] is the entry point.
use crate::gitlab_api::types::Response;
use chrono::{DateTime, Local, NaiveDate, NaiveTime};
use reqwest::blocking::Client;
use reqwest::header::AUTHORIZATION;
use serde_json::json;

const GRAPHQL_TEMPLATE: &str = include_str!("./gitlab-query.graphql");

/// Transforms a [`NaiveDate`] to a `DateTime<Local>`.
fn naive_date_to_local_datetime(date: NaiveDate) -> DateTime<Local> {
date.and_time(NaiveTime::MIN)
.and_local_timezone(Local)
.unwrap()
}

/// Performs a single request against the GitLab API, getting exactly one page
/// of the paged data source. The data is filtered for the date span to make the
/// request smaller/quicker.
///
/// # Parameters
/// - `username`: The exact GitLab username of the user.
/// - `host`: Host name of the GitLab instance without `https://`
/// - `token`: GitLab token to access the GitLab instance. Must have at least
/// READ access.
/// - `before`: Identifier from previous request to get the next page of the
/// paginated result.
/// - `start_date`: Inclusive begin date.
/// - `end_date`: Inclusive end date.
fn fetch_result(
username: &str,
host: &str,
token: &str,
before: Option<&str>,
start_date: NaiveDate,
end_date: NaiveDate,
) -> Response {
let graphql_query = GRAPHQL_TEMPLATE
.replace("%USERNAME%", username)
.replace("%BEFORE%", before.unwrap_or_default())
// GitLab API ignores the time component and just looks at the
// date and the timezone.
.replace(
"%START_DATE%",
naive_date_to_local_datetime(start_date)
.to_string()
.as_str(),
)
// GitLab API ignores the time component and just looks at the
// date and the timezone.
.replace(
"%END_DATE%",
naive_date_to_local_datetime(end_date).to_string().as_str(),
);
let payload = json!({ "query": graphql_query });

let authorization = format!("Bearer {token}", token = token);
let url = format!("https://{host}/api/graphql", host = host);
let client = Client::new();

client
.post(url)
.header(AUTHORIZATION, authorization)
.json(&payload)
.send()
.unwrap()
.json::<Response>()
.unwrap()
}

/// Fetches all results from the API with pagination in mind.
///
/// # Parameters
/// - `username`: The exact GitLab username of the user.
/// - `host`: Host name of the GitLab instance without `https://`
/// - `token`: GitLab token to access the GitLab instance. Must have at least
/// READ access.
/// - `start_date`: Inclusive begin date.
/// - `end_date`: Inclusive end date.
pub fn fetch_results(
username: &str,
host: &str,
token: &str,
start_date: NaiveDate,
end_date: NaiveDate,
) -> Response {
let base = fetch_result(username, host, token, None, start_date, end_date);

let mut aggregated = base;
while aggregated.data.timelogs.pageInfo.hasPreviousPage {
let mut next = fetch_result(
username,
host,
token,
Some(
&aggregated
.data
.timelogs
.pageInfo
.startCursor
.expect("Should be valid string at this point"),
),
start_date,
end_date,
);

// Ordering here is not that important, happens later anyway.
next.data
.timelogs
.nodes
.extend(aggregated.data.timelogs.nodes);
aggregated = next;
}
aggregated
}
Loading

0 comments on commit d1c6ed3

Please sign in to comment.