From a3bf4afe51d176f051c4c54da88974b8070a3ce9 Mon Sep 17 00:00:00 2001 From: Hubert Date: Sun, 18 Jul 2021 07:46:14 +0200 Subject: [PATCH] save --- src/error.rs | 16 +++++ src/git.rs | 84 +------------------------ src/gitcommit.rs | 20 ++++++ src/gitdir.rs | 14 +++++ src/gitfile.rs | 21 +++++++ src/gitrepo.rs | 58 +++++++++++++++++ src/main.rs | 152 +++++++++++++++++++++++++++------------------ templates/git.html | 7 ++- 8 files changed, 229 insertions(+), 143 deletions(-) create mode 100644 src/error.rs create mode 100644 src/gitcommit.rs create mode 100644 src/gitdir.rs create mode 100644 src/gitfile.rs create mode 100644 src/gitrepo.rs diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..9beb7f3 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,16 @@ +use actix_web::dev::HttpResponseBuilder; +use actix_web::http::StatusCode; + +pub struct Error(String); + +impl From for Error { + fn from(giterr: git2::Error) -> Self { + Error(giterr.to_string()) + } +} + +impl From for actix_web::error::Error { + fn from(_: Error) -> Self { + HttpResponseBuilder::new(StatusCode::BAD_GATEWAY).body("").into() + } +} \ No newline at end of file diff --git a/src/git.rs b/src/git.rs index b3d88c8..28a4ea6 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,88 +1,10 @@ use std::fmt::{Display, Formatter}; -use git2::{Reference, Commit, Tree, ObjectType, Repository, Oid}; use std::ops::Add; +use git2::{Commit, ObjectType, Oid, Reference, Repository, Tree}; -pub struct GitRepo { - git2 : Repository, -} - -impl GitRepo { - - pub fn new(path : &str) -> Result { - Repository::open(path).map(|git2| GitRepo{git2}) - } - - pub fn get_root_tree<'a, 'b> (&'a self, commit : &'b GitCommit) -> Result, git2::Error> { - let oid = Oid::from_str(&commit.0)?; - let commit = self.git2.find_commit(oid)?; - let tree = commit.tree()?; - let fullname = "/".to_string(); - Ok(GitDir { fullname, tree }) - } - - pub async fn browse<'a>(&'a self, dir: &GitDir<'a>) -> Result>, git2::Error> { - let mut res = Vec::new(); - for entry in dir.tree.iter() { - match entry.kind() { - None => {Err(git2::Error::from_str("each tree entry must be well defined"))?;} - Some(kind) => match kind { - ObjectType::Any => {Err(git2::Error::from_str("tree entry cannot be of kind Any"))?;} - ObjectType::Commit => {Err(git2::Error::from_str("tree entry cannot be of kind Commit"))?;} - ObjectType::Tree => { - let name = entry.name().ok_or(git2::Error::from_str("entry must have valid utf8 name"))?; - let fullname = dir.fullname.clone().add(name); - let subtree = self.git2.find_tree(entry.id())?; - res.push(GitBrowseEntry::EGitDir(GitDir {fullname, tree : subtree})); - } - ObjectType::Blob => { - let name = entry.name().ok_or(git2::Error::from_str("entry must have valid utf8 name"))?; - let fullname = dir.fullname.clone().add(name); - res.push(GitBrowseEntry::EGitFile(GitFile(fullname))); - } - ObjectType::Tag => {Err(git2::Error::from_str("tree entry cannot be of kind tag"))?;} - } - }; - } - return Ok(res); - } - -} - -#[derive(Debug)] -pub struct GitCommit (String); - -impl GitCommit { - pub fn new(s : String) -> GitCommit { - GitCommit(s) - } -} - -impl Display for GitCommit { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.0) - } -} - -#[derive(Debug)] -pub struct GitFile(String); -#[derive(Debug)] -pub struct GitDir<'a>{ - fullname: String, - tree : git2::Tree<'a>, -} - -impl Display for GitFile { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.0) - } -} - -impl Display for GitDir<'_> { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.fullname) - } -} +use crate::gitdir::GitDir; +use crate::gitfile::GitFile; #[derive(Debug)] pub enum GitBrowseEntry<'a> { diff --git a/src/gitcommit.rs b/src/gitcommit.rs new file mode 100644 index 0000000..2a2f400 --- /dev/null +++ b/src/gitcommit.rs @@ -0,0 +1,20 @@ +use std::fmt::{Display, Formatter}; + +#[derive(Debug)] +pub struct GitCommit (String); + +impl GitCommit { + pub fn new(s : String) -> GitCommit { + GitCommit(s) + } + + pub fn value(&self) -> &String { + &self.0 + } +} + +impl Display for GitCommit { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/src/gitdir.rs b/src/gitdir.rs new file mode 100644 index 0000000..03ca861 --- /dev/null +++ b/src/gitdir.rs @@ -0,0 +1,14 @@ +use std::fmt::{Display, Formatter}; +use std::path::PathBuf; + +#[derive(Debug)] +pub struct GitDir<'a>{ + pub fullname: PathBuf, + pub tree : git2::Tree<'a>, +} + +impl Display for GitDir<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.fullname.display()) + } +} diff --git a/src/gitfile.rs b/src/gitfile.rs new file mode 100644 index 0000000..1985088 --- /dev/null +++ b/src/gitfile.rs @@ -0,0 +1,21 @@ +use std::fmt::{Display, Formatter}; +use std::path::{PathBuf}; +use std::ffi::OsStr; + +#[derive(Debug)] +pub struct GitFile(pub PathBuf); + +impl GitFile { + pub(crate) fn new(fullname : PathBuf) -> GitFile { + GitFile(fullname) + } + pub fn name(&self) -> Option<&OsStr> { + self.0.file_name() + } +} + +impl Display for GitFile { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0.display()) + } +} diff --git a/src/gitrepo.rs b/src/gitrepo.rs new file mode 100644 index 0000000..ac19e77 --- /dev/null +++ b/src/gitrepo.rs @@ -0,0 +1,58 @@ +use std::ops::Add; + +use git2::{ObjectType, Oid, Repository}; + +use crate::git::GitBrowseEntry; +use crate::gitcommit::GitCommit; +use crate::gitdir::GitDir; +use crate::gitfile::GitFile; +use std::path::PathBuf; +use std::str::FromStr; + +pub struct GitRepo { + git2 : Repository, +} + +impl GitRepo { + + pub fn new(path : &str) -> Result { + Repository::open(path).map(|git2| GitRepo{git2}) + } + + pub fn get_root_tree<'a, 'b> (&'a self, commit : &'b GitCommit) -> Result, git2::Error> { + let oid = Oid::from_str(commit.value().as_str())?; + let commit = self.git2.find_commit(oid)?; + let tree = commit.tree()?; + let fullname = PathBuf::from("/"); + Ok(GitDir { fullname, tree }) + } + + pub async fn browse<'a>(&'a self, dir: &GitDir<'a>) -> Result>, git2::Error> { + let mut res = Vec::new(); + for entry in dir.tree.iter() { + match entry.kind() { + None => {Err(git2::Error::from_str("each tree entry must be well defined"))?;} + Some(kind) => match kind { + ObjectType::Any => {Err(git2::Error::from_str("tree entry cannot be of kind Any"))?;} + ObjectType::Commit => {Err(git2::Error::from_str("tree entry cannot be of kind Commit"))?;} + ObjectType::Tree => { + let name = entry.name().ok_or(git2::Error::from_str("entry must have valid utf8 name"))?; + let mut fullname = dir.fullname.clone(); + fullname.push(name); + let subtree = self.git2.find_tree(entry.id())?; + res.push(GitBrowseEntry::EGitDir(GitDir {fullname, tree : subtree})); + } + ObjectType::Blob => { + let name = entry.name().ok_or(git2::Error::from_str("entry must have valid utf8 name"))?; + let mut fullname = dir.fullname.clone(); + fullname.push(name); + res.push(GitBrowseEntry::EGitFile(GitFile::new(fullname))); + } + ObjectType::Tag => {Err(git2::Error::from_str("tree entry cannot be of kind tag"))?;} + } + }; + } + return Ok(res); + } + +} diff --git a/src/main.rs b/src/main.rs index d9e4b9b..494a59e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,41 +1,53 @@ +use std::collections::HashMap; +use std::io; +use std::io::{BufRead, ErrorKind, Read, Write}; +use std::ops::Add; +use std::path::{Path, PathBuf}; +use std::process::Stdio; + +use actix_files::Files; +use actix_session::{CookieSession, Session}; +use actix_web::{App, Error, get, HttpMessage, HttpRequest, HttpResponse, HttpServer, post, Responder, web}; +use actix_web::client::PayloadError; +use actix_web::dev::ServiceRequest; +use actix_web::http::{header, StatusCode}; +use actix_web::http::header::Header; +use actix_web::http::header::IntoHeaderValue; +use actix_web::middleware::Logger; +use actix_web::web::{Buf, Bytes}; +use actix_web_httpauth::extractors::AuthenticationError; +use actix_web_httpauth::extractors::basic::{BasicAuth, Config}; +use actix_web_httpauth::headers::authorization::{Authorization, Basic}; +use actix_web_httpauth::middleware::HttpAuthentication; +use askama_actix::Template; +use env_logger::Env; +use futures::{future, pin_mut, Stream, stream, StreamExt, TryFutureExt, TryStreamExt}; +use git2::ObjectType; +use serde::Deserialize; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdout, Command}; + +use gitcommit::GitCommit; +use gitdir::GitDir; +use gitrepo::GitRepo; + +use crate::git::GitBrowseEntry; +use crate::gitust::Gitust; +use crate::ite::SuperIterator; +use crate::reader::ToStream; +use crate::writer::Writer; +use crate::gitfile::GitFile; + mod git; mod ite; mod reader; mod writer; mod gitust; - -use actix_files::Files; -use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Error, HttpRequest, HttpMessage}; -use askama_actix::Template; -use actix_session::{Session, CookieSession}; -use actix_web_httpauth::headers::authorization::{Authorization, Basic}; -use actix_web::http::header::Header; -use actix_web_httpauth::middleware::HttpAuthentication; -use actix_web::dev::ServiceRequest; -use actix_web_httpauth::extractors::basic::{BasicAuth, Config}; -use actix_web_httpauth::extractors::AuthenticationError; -use crate::git::{GitBrowseEntry, GitRepo, GitCommit, GitDir}; -use actix_web::middleware::Logger; -use env_logger::Env; -use crate::ite::SuperIterator; -use std::ops::Add; -use std::path::{PathBuf, Path}; -use serde::Deserialize; -use tokio::process::{Command, Child, ChildStdout}; -use tokio::io::{AsyncWriteExt, AsyncBufReadExt, AsyncReadExt, BufReader}; -use std::process::Stdio; -use actix_web::http::{header, StatusCode}; -use std::io; -use std::collections::HashMap; -use std::io::{Read, BufRead, Write, ErrorKind}; -use futures::{Stream, StreamExt, TryStreamExt, future, stream, TryFutureExt, pin_mut}; -use actix_web::web::{Buf, Bytes}; -use actix_web::http::header::IntoHeaderValue; -use actix_web::client::PayloadError; -use crate::reader::ToStream; -use crate::writer::Writer; -use crate::gitust::Gitust; -use git2::ObjectType; +mod gitdir; +mod gitrepo; +mod gitcommit; +mod gitfile; +mod error; #[derive(Template)] #[template(path = "hello.html")] @@ -56,10 +68,15 @@ struct Repository { owner : Owner, } +enum Entry { + Dir(String), + File(String), +} + #[derive(Template)] #[template(path = "git.html")] struct GitMainTemplate -where for <'a> &'a TS : IntoIterator, +where for <'a> &'a TS : IntoIterator, for <'a> &'a ROOT : IntoIterator, { repo : Repository, @@ -133,7 +150,7 @@ async fn git_main( web::Path((ownername, reponame)): web::Path<(String, String)>, web::Query(GitWebQ{commit : commitnameopt, path : pathopt}) : web::Query, gitust : web::Data -) -> impl Responder { +) -> Result, Vec<(String, String)>>, error::Error> { let commitname = match commitnameopt { None => {"master".to_string()} Some(s) => {s} @@ -151,34 +168,47 @@ async fn git_main( let href = b + "/" + str_ref; ((str_ref.to_string(), href.clone()), href) }).collect(); - let repogit = match git2::Repository::open(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name)) { - Ok(repo) => repo, - Err(e) => panic!("failed to open: {}", e), - }; - let head = match repogit.head() { - Ok(head) => head, - Err(e) => panic!("failed to get head: {}", e) - }; - let commitgit = match head.peel_to_commit() { - Ok(commit) => commit, - Err(e) => panic!("failed to get commit: {}", e) - }; - let tree = match commitgit.tree() { - Ok(tree) => tree, - Err(e) => panic!("failed to get tree: {}", e) - }; - for entry in tree.iter() { - println!("{:?}", entry.name()); - println!("{:?}", entry.kind()); - if entry.kind() == Some(ObjectType::Tree) { - let subtree = repogit.find_tree(entry.id()).expect("this pust be a tree"); - println!("{:?}", subtree); - } - } + // let repogit = match git2::Repository::open(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name)) { + // Ok(repo) => repo, + // Err(e) => panic!("failed to open: {}", e), + // }; + // let head = match repogit.head() { + // Ok(head) => head, + // Err(e) => panic!("failed to get head: {}", e) + // }; + // let commitgit = match head.peel_to_commit() { + // Ok(commit) => commit, + // Err(e) => panic!("failed to get commit: {}", e) + // }; + // let tree = match commitgit.tree() { + // Ok(tree) => tree, + // Err(e) => panic!("failed to get tree: {}", e) + // }; + // for entry in tree.iter() { + // println!("{:?}", entry.name()); + // println!("{:?}", entry.kind()); + // if entry.kind() == Some(ObjectType::Tree) { + // let subtree = repogit.find_tree(entry.id()).expect("this pust be a tree"); + // println!("{:?}", subtree); + // } + // } let root = gitrepo.get_root_tree(&commit)?; // let root = GitBrowseDir::new(rootname); - let browse = gitrepo.browse(&root).await; - Ok(GitMainTemplate { repo, browse : browse, root : path, user_opt : Some(user)}) + let browse = gitrepo.browse(&root).await?; + let mut entries : Vec = Vec::new(); + for entry in browse { + match entry { + GitBrowseEntry::EGitFile(GitFile(fullname)) => { + let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?; + entries.push(Entry::File(format!("{}",osstr.to_string_lossy()))); + } + GitBrowseEntry::EGitDir(GitDir{fullname, .. }) => { + let osstr = fullname.file_name().ok_or(git2::Error::from_str("file name not defined"))?; + entries.push(Entry::Dir(format!("{}",osstr.to_string_lossy()))); + } + } + } + Ok(GitMainTemplate { repo, browse : entries, root : path, user_opt : Some(user)}) } //#[get("/git/{owner}/{repo}.git/{path:.*}")] async fn git_proto( diff --git a/templates/git.html b/templates/git.html index d713d54..031cfd1 100644 --- a/templates/git.html +++ b/templates/git.html @@ -75,7 +75,12 @@
    {% for entry in browse %} -
  • {{ entry }}
  • + {% match entry %} + {% when Entry::Dir with (name) %} +
  • {{ name }}
  • + {% when Entry::File with (name) %} +
  • {{ name }}
  • + {% endmatch %} {% endfor %}