This commit is contained in:
Hubert 2021-07-18 07:46:14 +02:00
parent a2dcab2ea8
commit a3bf4afe51
8 changed files with 229 additions and 143 deletions

16
src/error.rs Normal file
View File

@ -0,0 +1,16 @@
use actix_web::dev::HttpResponseBuilder;
use actix_web::http::StatusCode;
pub struct Error(String);
impl From<git2::Error> for Error {
fn from(giterr: git2::Error) -> Self {
Error(giterr.to_string())
}
}
impl From<Error> for actix_web::error::Error {
fn from(_: Error) -> Self {
HttpResponseBuilder::new(StatusCode::BAD_GATEWAY).body("").into()
}
}

View File

@ -1,88 +1,10 @@
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use git2::{Reference, Commit, Tree, ObjectType, Repository, Oid};
use std::ops::Add; use std::ops::Add;
use git2::{Commit, ObjectType, Oid, Reference, Repository, Tree};
pub struct GitRepo { use crate::gitdir::GitDir;
git2 : Repository, use crate::gitfile::GitFile;
}
impl GitRepo {
pub fn new(path : &str) -> Result<GitRepo, git2::Error> {
Repository::open(path).map(|git2| GitRepo{git2})
}
pub fn get_root_tree<'a, 'b> (&'a self, commit : &'b GitCommit) -> Result<GitDir<'a>, 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<Vec<GitBrowseEntry<'a>>, 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)
}
}
#[derive(Debug)] #[derive(Debug)]
pub enum GitBrowseEntry<'a> { pub enum GitBrowseEntry<'a> {

20
src/gitcommit.rs Normal file
View File

@ -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)
}
}

14
src/gitdir.rs Normal file
View File

@ -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())
}
}

21
src/gitfile.rs Normal file
View File

@ -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())
}
}

58
src/gitrepo.rs Normal file
View File

@ -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<GitRepo, git2::Error> {
Repository::open(path).map(|git2| GitRepo{git2})
}
pub fn get_root_tree<'a, 'b> (&'a self, commit : &'b GitCommit) -> Result<GitDir<'a>, 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<Vec<GitBrowseEntry<'a>>, 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);
}
}

View File

@ -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 git;
mod ite; mod ite;
mod reader; mod reader;
mod writer; mod writer;
mod gitust; mod gitust;
mod gitdir;
use actix_files::Files; mod gitrepo;
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Error, HttpRequest, HttpMessage}; mod gitcommit;
use askama_actix::Template; mod gitfile;
use actix_session::{Session, CookieSession}; mod error;
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;
#[derive(Template)] #[derive(Template)]
#[template(path = "hello.html")] #[template(path = "hello.html")]
@ -56,10 +68,15 @@ struct Repository {
owner : Owner, owner : Owner,
} }
enum Entry {
Dir(String),
File(String),
}
#[derive(Template)] #[derive(Template)]
#[template(path = "git.html")] #[template(path = "git.html")]
struct GitMainTemplate<TS, ROOT> struct GitMainTemplate<TS, ROOT>
where for <'a> &'a TS : IntoIterator<Item = &'a GitBrowseEntry>, where for <'a> &'a TS : IntoIterator<Item = &'a Entry>,
for <'a> &'a ROOT : IntoIterator<Item = &'a (String, String)>, for <'a> &'a ROOT : IntoIterator<Item = &'a (String, String)>,
{ {
repo : Repository, repo : Repository,
@ -133,7 +150,7 @@ async fn git_main(
web::Path((ownername, reponame)): web::Path<(String, String)>, web::Path((ownername, reponame)): web::Path<(String, String)>,
web::Query(GitWebQ{commit : commitnameopt, path : pathopt}) : web::Query<GitWebQ>, web::Query(GitWebQ{commit : commitnameopt, path : pathopt}) : web::Query<GitWebQ>,
gitust : web::Data<Gitust> gitust : web::Data<Gitust>
) -> impl Responder { ) -> Result<GitMainTemplate<Vec<Entry>, Vec<(String, String)>>, error::Error> {
let commitname = match commitnameopt { let commitname = match commitnameopt {
None => {"master".to_string()} None => {"master".to_string()}
Some(s) => {s} Some(s) => {s}
@ -151,34 +168,47 @@ async fn git_main(
let href = b + "/" + str_ref; let href = b + "/" + str_ref;
((str_ref.to_string(), href.clone()), href) ((str_ref.to_string(), href.clone()), href)
}).collect(); }).collect();
let repogit = match git2::Repository::open(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name)) { // let repogit = match git2::Repository::open(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name)) {
Ok(repo) => repo, // Ok(repo) => repo,
Err(e) => panic!("failed to open: {}", e), // Err(e) => panic!("failed to open: {}", e),
}; // };
let head = match repogit.head() { // let head = match repogit.head() {
Ok(head) => head, // Ok(head) => head,
Err(e) => panic!("failed to get head: {}", e) // Err(e) => panic!("failed to get head: {}", e)
}; // };
let commitgit = match head.peel_to_commit() { // let commitgit = match head.peel_to_commit() {
Ok(commit) => commit, // Ok(commit) => commit,
Err(e) => panic!("failed to get commit: {}", e) // Err(e) => panic!("failed to get commit: {}", e)
}; // };
let tree = match commitgit.tree() { // let tree = match commitgit.tree() {
Ok(tree) => tree, // Ok(tree) => tree,
Err(e) => panic!("failed to get tree: {}", e) // Err(e) => panic!("failed to get tree: {}", e)
}; // };
for entry in tree.iter() { // for entry in tree.iter() {
println!("{:?}", entry.name()); // println!("{:?}", entry.name());
println!("{:?}", entry.kind()); // println!("{:?}", entry.kind());
if entry.kind() == Some(ObjectType::Tree) { // if entry.kind() == Some(ObjectType::Tree) {
let subtree = repogit.find_tree(entry.id()).expect("this pust be a tree"); // let subtree = repogit.find_tree(entry.id()).expect("this pust be a tree");
println!("{:?}", subtree); // println!("{:?}", subtree);
} // }
} // }
let root = gitrepo.get_root_tree(&commit)?; let root = gitrepo.get_root_tree(&commit)?;
// let root = GitBrowseDir::new(rootname); // let root = GitBrowseDir::new(rootname);
let browse = gitrepo.browse(&root).await; let browse = gitrepo.browse(&root).await?;
Ok(GitMainTemplate { repo, browse : browse, root : path, user_opt : Some(user)}) let mut entries : Vec<Entry> = 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:.*}")] //#[get("/git/{owner}/{repo}.git/{path:.*}")]
async fn git_proto( async fn git_proto(

View File

@ -75,7 +75,12 @@
<ul class="filebrowser"> <ul class="filebrowser">
{% for entry in browse %} {% for entry in browse %}
<li><i class="fa fa-folder"></i> {{ entry }}</li> {% match entry %}
{% when Entry::Dir with (name) %}
<li><i class="fa fa-folder"></i> {{ name }}</li>
{% when Entry::File with (name) %}
<li><i class="fa fa-folder"></i> {{ name }}</li>
{% endmatch %}
{% endfor %} {% endfor %}
</ul> </ul>
</div> </div>