Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::env;
- use reqwest::header::{ HeaderMap, HeaderValue };
- use reqwest;
- const GITLAB_URL: &str = "https://git.svc.shore.to/api/v4";
- pub enum TokenListType {
- Group,
- Project,
- // Token,
- }
- pub struct TokenList {
- pub _type: TokenListType,
- pub id: Option<i64>,
- data: Option<serde_json::Value>,
- }
- #[derive(Debug)]
- pub struct ErrorResponse {
- pub message: String,
- }
- impl TokenList {
- pub fn new(_type: TokenListType, _id: Option<i64>) -> Self {
- TokenList { _type: _type, id: _id, data: None }
- }
- pub fn run(&mut self) -> Result<&mut TokenList, ErrorResponse> {
- let gitlab_token: String = env::var("gitlab_token").expect("GITLAB_TOKEN must be set");
- let mut headers = HeaderMap::new();
- headers.insert("PRIVATE-TOKEN", HeaderValue::from_str(&gitlab_token).unwrap());
- let client = reqwest::blocking::Client::new();
- let mut endpoint: String = match self._type {
- TokenListType::Group => "groups".to_owned(),
- TokenListType::Project => "projects".to_owned(),
- // TokenListType::Token => "tokens".to_owned(),
- };
- if self.id.is_some() {
- endpoint = format!("{}/{}/access_tokens", endpoint, self.id.unwrap());
- }
- let final_url = format!("{GITLAB_URL}/{endpoint}");
- // println!("######### Endpoint {}", final_url);
- let response = client
- .get(final_url)
- .headers(headers)
- .send()
- .map_err(|e|
- Err::<String, ErrorResponse>(ErrorResponse {
- message: format!("Response Error: {}", e),
- })
- );
- let value = response
- .unwrap()
- .json::<serde_json::Value>()
- .map_err(|e| ErrorResponse { message: format!("Error Parsing Json") });
- match value {
- Ok(val) => {
- self.data = Some(val);
- Ok(self)
- }
- Err(e) =>
- Err(ErrorResponse {
- message: format!("Error getting values from json {:?}", e),
- }),
- }
- }
- pub fn print(&self) -> () {
- println!("Project Name, Project ID, Token Name, Expire Date\n");
- if let Some(projects) = self.data.as_ref().and_then(|val| val.as_array()) {
- projects.iter().for_each(|value| {
- // println!("{:?},{:?} ", value["name"], value["id"].as_i64());
- let pro_name = value["name"].as_str();
- let pro_id = value["id"].as_i64();
- let mut token_request = TokenList::new(
- TokenListType::Project,
- value["id"].as_i64()
- );
- let _ = token_request.run();
- if let Some(tokens) = token_request.data.as_ref().and_then(|val| val.as_array()) {
- tokens.iter().for_each(|val| {
- println!(
- "{:?}, {:?}, {:?}, {:?}",
- pro_name,
- pro_id,
- val["name"].as_str(),
- val["id"].as_i64()
- );
- });
- }
- })
- };
- }
- }
- // main.src
- //
- // use lib::{ TokenList, TokenListType };
- // fn main() {
- // // println!("Hello, world!");
- // let mut group_list = TokenList::new(TokenListType::Project, None);
- // let result = group_list.run();
- // result.expect("Cannot Print").print()
- // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement