Compare commits

...

4 Commits

Author SHA1 Message Date
Hubert aa656d3a19 head 2021-07-18 14:40:56 +02:00
Hubert 82757ef9eb works a bit 2021-07-18 14:34:06 +02:00
Hubert 2278b46a88 compile 2021-07-18 14:01:04 +02:00
Hubert a3bf4afe51 save 2021-07-18 07:46:14 +02:00
8 changed files with 237 additions and 151 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(e: Error) -> Self {
HttpResponseBuilder::new(StatusCode::BAD_GATEWAY).body(e.0).into()
}
}

View File

@ -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<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)
}
}
use crate::gitdir::GitDir;
use crate::gitfile::GitFile;
#[derive(Debug)]
pub enum GitBrowseEntry<'a> {

28
src/gitcommit.rs Normal file
View File

@ -0,0 +1,28 @@
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum GitRef{
Commit(String),
Branch(String),
Head,
}
impl GitRef {
pub fn new_commit(s : String) -> GitRef {
GitRef::Commit(s)
}
pub fn new_branch(s : String) -> GitRef {
GitRef::Branch(s)
}
}
impl Display for GitRef {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", match &self {
GitRef::Commit(s) => {s.as_str()}
GitRef::Branch(s) => {s.as_str()}
GitRef::Head => {"HEAD"}
})
}
}

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

71
src/gitrepo.rs Normal file
View File

@ -0,0 +1,71 @@
use std::ops::Add;
use git2::{ObjectType, Oid, Repository, BranchType};
use crate::git::GitBrowseEntry;
use crate::gitcommit::GitRef;
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 GitRef) -> Result<GitDir<'a>, git2::Error> {
let commit = match commit {
GitRef::Commit(commit) => {
let oid = Oid::from_str(commit.as_str())?;
self.git2.find_commit(oid)?
}
GitRef::Branch(branch) => {
let branch = self.git2.find_branch(branch.as_str(), BranchType::Local)?;
branch.get().peel_to_commit()?
}
GitRef::Head => {
let head = self.git2.head()?;
head.peel_to_commit()?
}
};
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::GitRef;
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<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)>,
{
repo : Repository,
@ -107,6 +124,7 @@ async fn hello_auth(req : HttpRequest) -> impl Responder {
struct GitWebQ {
commit: Option<String>,
path: Option<String>,
branch: Option<String>,
}
@ -131,54 +149,45 @@ async fn chunk() -> HttpResponse {
#[get("/git/{owner}/{repo}.git")]
async fn git_main(
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, branch : branchopt}) : web::Query<GitWebQ>,
gitust : web::Data<Gitust>
) -> impl Responder {
let commitname = match commitnameopt {
None => {"master".to_string()}
Some(s) => {s}
};
) -> Result<GitMainTemplate<Vec<Entry>, Vec<(String, String)>>, error::Error> {
let rootname = match pathopt {
None => {"/".to_string()}
Some(s) => {s}
};
let commit = GitCommit::new(commitname);
let commit = match commitnameopt {
None => {match branchopt {
None => {GitRef::Head}
Some(s) => {GitRef::Branch(s)}
}}
Some(s) => {GitRef::Commit(s)}
};
let owner = Owner { name : ownername};
let repo = Repository {name : reponame, owner};
let user = User { name : "Hubert".to_string()};
let gitrepo = GitRepo::new(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name).as_str())?;
let path : Vec<(String, String)> = rootname.split("/").map_accum("/git/".to_string() + &ownername + "/" + &reponame + "/" + &commitname, |str_ref, b| {
// il faut ajouter le commit/branch dans la query
let path = rootname.split("/").map_accum("/git/".to_string() + &repo.owner.name + "/" + &repo.name, |str_ref, b| {
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 gitrepo = GitRepo::new(format!("{}/{}/{}.git", &gitust.repo_root_path, &repo.owner.name, &repo.name).as_str())?;
let root = gitrepo.get_root_tree(&commit)?;
let browse = gitrepo.browse(&root).await?;
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())));
}
}
}
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)})
Ok(GitMainTemplate { repo, browse : entries, root : path, user_opt : Some(user)})
}
//#[get("/git/{owner}/{repo}.git/{path:.*}")]
async fn git_proto(

View File

@ -75,7 +75,12 @@
<ul class="filebrowser">
{% 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 %}
</ul>
</div>