Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use libra in lunar app for clone and push code #531

Merged
merged 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,4 @@ ed25519-dalek = "2.1.1"
ctrlc = "3.4.4"
git2 = "0.19.0"
tempfile = "3.10.1"
home = "0.5.9"
4 changes: 2 additions & 2 deletions gateway/src/api/ztm_router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::api::MegaApiServiceState;
pub fn routers() -> Router<MegaApiServiceState> {
Router::new()
.route("/ztm/repo_provide", post(repo_provide))
.route("/ztm/repo_fork", get(repo_folk))
.route("/ztm/repo_fork", get(repo_fork))
.route("/ztm/peer_id", get(peer_id))
.route("/ztm/alias_to_path", get(alias_to_path))
}
Expand Down Expand Up @@ -59,7 +59,7 @@ async fn repo_provide(
Ok(Json(res))
}

async fn repo_folk(
async fn repo_fork(
Query(query): Query<HashMap<String, String>>,
state: State<MegaApiServiceState>,
) -> Result<Json<CommonResult<String>>, (StatusCode, String)> {
Expand Down
2 changes: 1 addition & 1 deletion gemini/src/http/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ pub async fn repo_folk_alias(ztm_agent_port: u16, identifier: String) -> Result<
Err(e) => return Err(e),
}

let msg = format!("git clone http://localhost:{local_port}{path}.git");
let msg = format!("http://localhost:{local_port}{path}.git");
Ok(msg)
}

Expand Down
7 changes: 5 additions & 2 deletions lunar/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"extends": "next/core-web-vitals"
}
"extends": "next/core-web-vitals",
"rules": {
"@next/next/no-img-element": "off" // disable it due to we use static export
}
}
1 change: 1 addition & 0 deletions lunar/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ tauri = { version = "1.7.1", features = [
"process-command-api",
] }
tokio = { workspace = true }
home = { workspace = true }

[dev-dependencies]
tokio = { workspace = true, features = ["macros"] }
Expand Down
4 changes: 4 additions & 0 deletions lunar/src-tauri/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ fn main() {
.unwrap();

let sidecar_path = format!("./binaries/mega-{}{}", target_triple, extension);
let libra_path = format!("./binaries/libra-{}{}", target_triple, extension);

let debug_path = if cfg!(debug_assertions) {
"debug"
Expand All @@ -40,6 +41,9 @@ fn main() {
std::fs::copy(format!("../../target/{}/mega{}", debug_path, extension), sidecar_path)
.expect("Run Cargo build for mega first");

std::fs::copy(format!("../../target/{}/libra{}", debug_path, extension), libra_path)
.expect("Run Cargo build for libra first");

// Copy libpipy due to target os
#[cfg(target_os = "macos")]
std::fs::copy(
Expand Down
83 changes: 80 additions & 3 deletions lunar/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::env;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::{env, fs};

use serde::Deserialize;
use tauri::api::process::{Command, CommandChild, CommandEvent};
Expand Down Expand Up @@ -129,11 +130,86 @@ fn restart_mega_service(
}

#[tauri::command]
async fn mega_service_status(state: State<'_, Arc<Mutex<ServiceState>>>) -> Result<(bool, bool), String> {
fn mega_service_status(state: State<'_, Arc<Mutex<ServiceState>>>) -> Result<(bool, bool), String> {
let service_state = state.lock().unwrap();
Ok((service_state.child.is_some(), service_state.with_relay))
}

#[tauri::command]
fn clone_repository(repo_url: String, name: String) -> Result<(), String> {
let home = match home::home_dir() {
Some(path) if !path.as_os_str().is_empty() => path,
_ => {
println!("Unable to get your home dir!");
PathBuf::new()
}
};
let target_dir = home.join(".mega").join(name.clone());

if target_dir.exists() {
fs::remove_dir_all(&target_dir).unwrap();
}

let output = Command::new_sidecar("libra")
.expect("Failed to create `libra` binary command")
.args(["clone", &repo_url, (target_dir.to_str().unwrap())])
.output()
.map_err(|e| format!("Failed to execute process: {}", e))?;

if output.status.success() {
println!("{}", output.stdout);
} else {
eprintln!("{}", output.stderr);
}
change_remote_url(target_dir.clone(), name)?;
push_to_new_remote(target_dir)?;
Ok(())
}

fn change_remote_url(repo_path: PathBuf, name: String) -> Result<(), String> {
Command::new_sidecar("libra")
.expect("Failed to create `libra` binary command")
.args(["remote", "remove", "origin"])
.current_dir(repo_path.clone())
.output()
.map_err(|e| format!("Failed to execute process: {}", e))?;

let output = Command::new_sidecar("libra")
.expect("Failed to create `libra` binary command")
.args([
"remote",
"add",
"origin",
&format!("http://localhost:8000/third-part/{}", name),
])
.current_dir(repo_path.clone())
.output()
.map_err(|e| format!("Failed to execute process: {}", e))?;

if output.status.success() {
println!("{}", output.stdout);
} else {
eprintln!("{}", output.stderr);
}
Ok(())
}

fn push_to_new_remote(repo_path: PathBuf) -> Result<(), String> {
let output = Command::new_sidecar("libra")
.expect("Failed to create `libra` binary command")
.args(["push", "origin", "master"])
.current_dir(repo_path)
.output()
.map_err(|e| format!("Failed to execute process: {}", e))?;

if output.status.success() {
println!("{}", output.stdout);
} else {
eprintln!("{}", output.stderr);
}
Ok(())
}

fn main() {
let params = MegaStartParams::default();
tauri::Builder::default()
Expand All @@ -142,7 +218,8 @@ fn main() {
start_mega_service,
stop_mega_service,
restart_mega_service,
mega_service_status
mega_service_status,
clone_repository
])
.setup(|app| {
let app_handle = app.handle().clone();
Expand Down
7 changes: 6 additions & 1 deletion lunar/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
{
"name": "binaries/mega",
"sidecar": true
},
{
"name": "binaries/libra",
"sidecar": true
}
]
},
Expand All @@ -35,7 +39,8 @@
"files": {}
},
"externalBin": [
"binaries/mega"
"binaries/mega",
"binaries/libra"
],
"icon": [
"icons/32x32.png",
Expand Down
26 changes: 22 additions & 4 deletions lunar/src/app/api/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import { invoke } from '@tauri-apps/api/tauri';
const endpoint = process.env.NEXT_PUBLIC_API_URL;
const relay = process.env.NEXT_PUBLIC_RELAY_API_URL;

export interface ApiResult<T> {
req_result: boolean,
data: T,
err_message: string
}

export class FetchError extends Error {
info: any;
status: number;
Expand Down Expand Up @@ -86,9 +92,9 @@ export function useRepoList() {
dedupingInterval: 30000,
})
return {
data: data,
isLoading,
isError: error,
repo: data,
isRepoLoading: isLoading,
isRepoError: error,
}
}

Expand All @@ -102,6 +108,18 @@ export function usePeerId() {
isError: error,
}
}

export function useRepoFork(identifier) {
const { data, error, isLoading } = useSWR(`${endpoint}/api/v1/mega/ztm/repo_fork?identifier=${identifier}`, {
dedupingInterval: 60000,
})
return {
url: data,
isForkLoading: isLoading,
isForkError: error,
}
}

// export function usePublishRepo(path: string) {
// const { data, error, isLoading } = useSWR(`${endpoint}/api/v1/mega/ztm/repo_provide?path=${path}`, fetcher)
// return {
Expand Down Expand Up @@ -144,4 +162,4 @@ export async function requestPublishRepo(data) {
throw new Error(errorMessage);
}
return response.json();
}
}
16 changes: 0 additions & 16 deletions lunar/src/app/api/relay/repo_fork/route.ts

This file was deleted.

18 changes: 15 additions & 3 deletions lunar/src/app/application-layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import {
import { invoke } from '@tauri-apps/api/tauri'
import { usePathname } from 'next/navigation'
import { useState, useEffect } from 'react'
import { Badge } from 'antd/lib'
import { Badge, Alert, Skeleton } from 'antd/lib'

function AccountDropdownMenu({ anchor }: { anchor: 'top start' | 'bottom end' }) {
return (
Expand Down Expand Up @@ -82,11 +82,14 @@ export function ApplicationLayout({
let pathname = usePathname()

const [mega_status, setMegaStatus] = useState(false)
const [ztm_status, setZtmStatus] = useState(true)

useEffect(() => {
const fetchStatus = () => {
invoke('mega_service_status')
.then((status: boolean) => {
setMegaStatus(status);
.then((status: boolean[]) => {
setMegaStatus(status[0]);
setZtmStatus(status[1]);
console.log(`Service Status: ${status}`);
})
.catch((error) => {
Expand Down Expand Up @@ -214,6 +217,15 @@ export function ApplicationLayout({
</Sidebar>
}
>
{
!ztm_status &&
<Alert
banner
message={
"Relay address is not configed, Some functions are not available"
}
/>
}
{children}
</SidebarLayout>
)
Expand Down
47 changes: 15 additions & 32 deletions lunar/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'

import { Flex, Layout, Skeleton, Alert } from "antd/lib";
import { Flex, Layout, Skeleton } from "antd/lib";
import CodeTable from '@/components/CodeTable';
import MergeList from '@/components/MergeList';
import { useTreeCommitInfo, useBlobContent, useMRList, useMegaStatus } from '@/app/api/fetcher';
Expand Down Expand Up @@ -44,36 +44,19 @@ export default function HomePage() {
if (isTreeLoading || isBlobLoading || isMRLoading || isLoading) return <Skeleton />;

return (
<div>
{
!status[1] &&
<Alert
banner
message={
"Relay address is not configed, Some functions are not available"
}
/>
}

{
<Flex gap="middle" wrap>
<Layout style={leftStyle}>
{
(tree && blob) &&
<CodeTable directory={tree.data} readmeContent={blob.data} with_ztm={status[1]} />
}
</Layout>
<Layout style={rightStyle}>
{(isTreeLoading || isBlobLoading) &&
<Skeleton />
}
{(!isTreeLoading && !isBlobLoading) &&
<MergeList mrList={mrList.data} />
}
{/* <Content style={contentStyle}></Content> */}
</Layout>
</Flex>
}
</div>
<Flex gap="middle" wrap>
<Layout style={leftStyle}>
{
(tree && blob) &&
<CodeTable directory={tree.data} readmeContent={blob.data} with_ztm={status[1]} />
}
</Layout>
<Layout style={rightStyle}>
{mrList &&
<MergeList mrList={mrList.data} />
}
{/* <Content style={contentStyle}></Content> */}
</Layout>
</Flex>
)
}
18 changes: 5 additions & 13 deletions lunar/src/app/repo/page.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
'use client'

import DataList from '@/components/DataList'
import { useRepoList } from '../api/fetcher';
import RepoList from '@/components/RepoList'
import { useMegaStatus, useRepoList } from '@/app/api/fetcher';
import { Skeleton } from "antd";


export default function RepoPage() {
const { data, isLoading, isError } = useRepoList();
const { repo, isRepoLoading, isRepoError } = useRepoList();

if (isRepoLoading) return <Skeleton />;
return (
<div>
{
isLoading &&
<Skeleton />
}
{
!isLoading &&
<DataList data={data} />
}
</div>
<RepoList data={repo} />
)
}
Loading
Loading