Skip to main content

kotoba/
cli.rs

1//! Kotoba CLI - Denoを参考にしたグラフ処理システムのコマンドラインインターフェース
2//!
3//! このモジュールはKotobaのメインCLIを提供し、Deno CLIを参考にした使いやすい
4//! インターフェースを実装します。
5
6use clap::{Parser, Subcommand};
7use std::path::PathBuf;
8
9/// Kotoba CLIのメイン構造体
10#[derive(Parser)]
11#[command(name = "kotoba")]
12#[command(about = "Kotoba - Graph processing system inspired by Deno")]
13#[command(version = env!("CARGO_PKG_VERSION"))]
14pub struct Cli {
15    #[command(subcommand)]
16    pub command: Commands,
17
18    /// 設定ファイルパス
19    #[arg(short, long, global = true)]
20    pub config: Option<PathBuf>,
21
22    /// ログレベル
23    #[arg(short, long, global = true, default_value = "info")]
24    pub log_level: String,
25
26    /// 作業ディレクトリ
27    #[arg(short = 'C', long, global = true)]
28    pub cwd: Option<PathBuf>,
29}
30
31/// Kotoba CLIのサブコマンド
32#[derive(Subcommand)]
33pub enum Commands {
34    /// .kotobaファイルを実行
35    Run {
36        /// 実行するファイル
37        file: PathBuf,
38
39        /// 引数
40        #[arg(trailing_var_arg = true)]
41        args: Vec<String>,
42
43        /// ウォッチモード
44        #[arg(short, long)]
45        watch: bool,
46
47        /// 許可する権限
48        #[arg(short = 'A', long)]
49        allow_all: bool,
50
51        /// ネットワークアクセスを許可
52        #[arg(long)]
53        allow_net: bool,
54
55        /// ファイルシステムアクセスを許可
56        #[arg(long)]
57        allow_read: bool,
58
59        /// 書き込みアクセスを許可
60        #[arg(long)]
61        allow_write: bool,
62    },
63
64    /// GQLクエリを実行
65    Query {
66        /// クエリファイルまたはクエリ文字列
67        query: String,
68
69        /// パラメータファイル
70        #[arg(short, long)]
71        params: Option<PathBuf>,
72
73        /// 出力フォーマット (json, graphson, text)
74        #[arg(short, long, default_value = "json")]
75        format: String,
76
77        /// インタラクティブモード
78        #[arg(short, long)]
79        interactive: bool,
80    },
81
82    /// グラフ書換えルールを適用
83    Rewrite {
84        /// 入力グラフファイル
85        input: PathBuf,
86
87        /// ルールファイル
88        rules: PathBuf,
89
90        /// 出力ファイル
91        #[arg(short, long)]
92        output: Option<PathBuf>,
93
94        /// 戦略 (once, exhaust, while, seq)
95        #[arg(short, long, default_value = "once")]
96        strategy: String,
97    },
98
99    /// ファイルを検証
100    Check {
101        /// 検証するファイル
102        files: Vec<PathBuf>,
103
104        /// すべてのファイルをチェック
105        #[arg(short, long)]
106        all: bool,
107
108        /// 修正を適用
109        #[arg(short, long)]
110        fix: bool,
111    },
112
113    /// ファイルをフォーマット
114    Fmt {
115        /// フォーマットするファイル
116        files: Vec<PathBuf>,
117
118        /// すべてのファイルをフォーマット
119        #[arg(short, long)]
120        all: bool,
121
122        /// チェックのみ(変更しない)
123        #[arg(short, long)]
124        check: bool,
125
126        /// 設定ファイル
127        #[arg(short, long)]
128        config: Option<PathBuf>,
129    },
130
131    /// プロジェクト/グラフ情報を表示
132    Info {
133        /// 詳細表示
134        #[arg(short, long)]
135        detailed: bool,
136
137        /// JSON形式で出力
138        #[arg(short, long)]
139        json: bool,
140    },
141
142    /// Jsonnetタスクを実行
143    Task {
144        /// タスク名
145        task: Option<String>,
146
147        /// タスクファイル
148        #[arg(short, long)]
149        file: Option<PathBuf>,
150
151        /// タスクリストを表示
152        #[arg(short, long)]
153        list: bool,
154    },
155
156    /// インタラクティブGQL REPL
157    Repl {
158        /// 履歴ファイル
159        #[arg(short, long)]
160        history: Option<PathBuf>,
161
162        /// 初期グラフファイル
163        #[arg(short, long)]
164        graph: Option<PathBuf>,
165    },
166
167    /// ファイルをコンパイル/変換
168    Compile {
169        /// 入力ファイル
170        input: PathBuf,
171
172        /// 出力ファイル
173        #[arg(short, long)]
174        output: Option<PathBuf>,
175
176        /// ターゲット言語 (typescript, rust, json, graphson)
177        #[arg(short, long, default_value = "typescript")]
178        target: String,
179
180        /// 最適化レベル
181        #[arg(short, long, default_value = "0")]
182        optimize: u8,
183    },
184
185    /// コードを生成
186    Generate {
187        /// 生成タイプ (types, client, server, docs)
188        #[arg(value_enum)]
189        generator: GeneratorType,
190
191        /// スキーマファイル
192        #[arg(short, long)]
193        schema: Option<PathBuf>,
194
195        /// 出力ディレクトリ
196        #[arg(short, long)]
197        output: Option<PathBuf>,
198
199        /// 言語 (typescript, rust, python)
200        #[arg(short, long, default_value = "typescript")]
201        lang: String,
202    },
203
204    /// デプロイ関連コマンド(開発中)
205    #[cfg(feature = "deploy")]
206    Deploy {
207        #[command(subcommand)]
208        command: DeployCommands,
209    },
210
211    /// HTTPサーバーを起動
212    Server {
213        /// ポート番号
214        #[arg(short, long, default_value = "3000")]
215        port: u16,
216
217        /// ホスト
218        #[arg(short = 'H', long, default_value = "127.0.0.1")]
219        host: String,
220
221        /// 設定ファイル
222        #[arg(short, long)]
223        config: Option<PathBuf>,
224
225        /// TLS有効化
226        #[arg(long)]
227        tls: bool,
228
229        /// 証明書ファイル
230        #[arg(long)]
231        cert: Option<PathBuf>,
232
233        /// 秘密鍵ファイル
234        #[arg(long)]
235        key: Option<PathBuf>,
236    },
237
238    /// キャッシュ管理
239    #[cfg(feature = "deploy")]
240    Cache {
241        #[command(subcommand)]
242        command: CacheCommands,
243    },
244
245    /// ドキュメント生成
246    Doc {
247        /// 入力ファイル
248        #[arg(short, long)]
249        input: Option<PathBuf>,
250
251        /// 出力ディレクトリ
252        #[arg(short, long, default_value = "./docs")]
253        output: PathBuf,
254
255        /// フォーマット (html, markdown, json)
256        #[arg(short, long, default_value = "html")]
257        format: String,
258
259        /// ブラウザで開く
260        #[arg(long)]
261        open: bool,
262    },
263
264    /// 新規プロジェクトを初期化
265    Init {
266        /// プロジェクト名
267        name: Option<String>,
268
269        /// テンプレート (basic, web, api, fullstack)
270        #[arg(short, long, default_value = "basic")]
271        template: String,
272
273        /// 初期化を強制
274        #[arg(short, long)]
275        force: bool,
276    },
277
278    /// バージョン情報を表示
279    Version,
280}
281
282/// コード生成タイプ
283#[derive(clap::ValueEnum, Clone)]
284pub enum GeneratorType {
285    /// TypeScript/Flow型定義
286    Types,
287    /// GraphQLクライアント
288    Client,
289    /// サーバースタブ
290    Server,
291    /// ドキュメント
292    Docs,
293}
294
295/// デプロイサブコマンド(既存のdeploy CLIを統合)
296#[cfg(feature = "deploy")]
297#[derive(Subcommand)]
298pub enum DeployCommands {
299    /// デプロイメントを作成
300    Deploy {
301        /// 設定ファイルパス
302        #[arg(short, long)]
303        config: Option<PathBuf>,
304
305        /// デプロイメント名
306        #[arg(short, long)]
307        name: Option<String>,
308
309        /// エントリーポイント
310        #[arg(short, long)]
311        entry_point: Option<String>,
312
313        /// ランタイムタイプ
314        #[arg(short, long)]
315        runtime: Option<String>,
316
317        /// ドメイン
318        #[arg(short, long)]
319        domain: Option<String>,
320
321        /// プロジェクトルート
322        #[arg(short, long)]
323        project: Option<PathBuf>,
324    },
325
326    /// デプロイメントを削除
327    Undeploy {
328        /// デプロイメントIDまたは名前
329        name: String,
330    },
331
332    /// デプロイメントの状態を表示
333    Status {
334        /// デプロイメントIDまたは名前
335        name: Option<String>,
336
337        /// すべてのデプロイメントを表示
338        #[arg(short, long)]
339        all: bool,
340    },
341
342    /// デプロイメントをスケーリング
343    Scale {
344        /// デプロイメントIDまたは名前
345        name: String,
346
347        /// ターゲットインスタンス数
348        instances: u32,
349    },
350
351    /// デプロイメントログを表示
352    Logs {
353        /// デプロイメントIDまたは名前
354        name: String,
355
356        /// フォロー
357        #[arg(short, long)]
358        follow: bool,
359
360        /// 行数
361        #[arg(short, long, default_value = "100")]
362        lines: usize,
363    },
364}
365
366/// キャッシュサブコマンド
367#[cfg(feature = "deploy")]
368#[derive(Subcommand)]
369pub enum CacheCommands {
370    /// キャッシュをクリア
371    Clear,
372
373    /// キャッシュ情報を表示
374    Info,
375
376    /// キャッシュディレクトリを表示
377    Dir,
378}
379
380/// CLI実行のメイン実装
381pub struct CliRunner {
382    // ここに必要なコンポーネントを追加
383}
384
385impl CliRunner {
386    /// 新しいCLIランナーを作成
387    pub fn new() -> Self {
388        Self {}
389    }
390
391    /// CLIコマンドを実行
392    pub async fn run(&self, cli: Cli) -> kotoba_core::types::Result<()> {
393        match cli.command {
394            Commands::Run { file, args, watch, allow_all, allow_net, allow_read, allow_write } => {
395                self.run_file(file, args, watch, allow_all, allow_net, allow_read, allow_write).await
396            }
397            Commands::Query { query, params, format, interactive } => {
398                self.run_query(query, params, format, interactive).await
399            }
400            Commands::Rewrite { input, rules, output, strategy } => {
401                self.run_rewrite(input, rules, output, strategy).await
402            }
403            Commands::Check { files, all, fix } => {
404                self.run_check(files, all, fix).await
405            }
406            Commands::Fmt { files, all, check, config } => {
407                self.run_fmt(files, all, check, config).await
408            }
409            Commands::Info { detailed, json } => {
410                self.run_info(detailed, json).await
411            }
412            Commands::Task { task, file, list } => {
413                self.run_task(task, file, list).await
414            }
415            Commands::Repl { history, graph } => {
416                self.run_repl(history, graph).await
417            }
418            Commands::Compile { input, output, target, optimize } => {
419                self.run_compile(input, output, target, optimize).await
420            }
421            Commands::Generate { generator, schema, output, lang } => {
422                self.run_generate(generator, schema, output, lang).await
423            }
424            #[cfg(feature = "deploy")]
425            Commands::Deploy { command } => {
426                self.run_deploy(command).await
427            }
428            Commands::Server { port, host, config, tls, cert, key } => {
429                self.run_server(port, host, config, tls, cert, key).await
430            }
431            #[cfg(feature = "deploy")]
432            Commands::Cache { command } => {
433                self.run_cache(command).await
434            }
435            Commands::Doc { input, output, format, open } => {
436                self.run_doc(input, output, format, open).await
437            }
438            Commands::Init { name, template, force } => {
439                self.run_init(name, template, force).await
440            }
441            Commands::Version => {
442                self.show_version();
443                Ok(())
444            }
445        }
446    }
447
448    // 各コマンドの実装(基本的な実装)
449    async fn run_file(&self, file: PathBuf, _args: Vec<String>, _watch: bool, _allow_all: bool, _allow_net: bool, _allow_read: bool, _allow_write: bool) -> kotoba_core::types::Result<()> {
450        println!("🚀 Running file: {}", file.display());
451        println!("💡 File execution not yet implemented");
452        Ok(())
453    }
454
455    async fn run_query(&self, query: String, _params: Option<PathBuf>, format: String, _interactive: bool) -> kotoba_core::types::Result<()> {
456        println!("🔍 Executing query: {}", query);
457        println!("📄 Output format: {}", format);
458        println!("💡 GQL query execution not yet implemented");
459        Ok(())
460    }
461
462    async fn run_rewrite(&self, input: PathBuf, rules: PathBuf, output: Option<PathBuf>, strategy: String) -> kotoba_core::types::Result<()> {
463        println!("🔄 Applying rewrite rules...");
464        println!("📥 Input: {}", input.display());
465        println!("📋 Rules: {}", rules.display());
466        if let Some(out) = &output {
467            println!("📤 Output: {}", out.display());
468        }
469        println!("🎯 Strategy: {}", strategy);
470        println!("💡 Graph rewriting not yet implemented");
471        Ok(())
472    }
473
474    async fn run_check(&self, files: Vec<PathBuf>, all: bool, fix: bool) -> kotoba_core::types::Result<()> {
475        if all {
476            println!("✅ Checking all files...");
477        } else {
478            println!("✅ Checking {} files...", files.len());
479            for file in &files {
480                println!("  {}", file.display());
481            }
482        }
483        if fix {
484            println!("🔧 Auto-fix enabled");
485        }
486        println!("💡 File validation not yet implemented");
487        Ok(())
488    }
489
490    async fn run_fmt(&self, files: Vec<PathBuf>, all: bool, check: bool, _config: Option<PathBuf>) -> kotoba_core::types::Result<()> {
491        if all {
492            println!("🎨 Formatting all files...");
493        } else {
494            println!("🎨 Formatting {} files...", files.len());
495            for file in &files {
496                println!("  {}", file.display());
497            }
498        }
499        if check {
500            println!("🔍 Check-only mode");
501        }
502        println!("💡 File formatting not yet implemented");
503        Ok(())
504    }
505
506    async fn run_info(&self, detailed: bool, json: bool) -> kotoba_core::types::Result<()> {
507        println!("ℹ️  Kotoba Project Information");
508        println!("=============================");
509        println!("🏷️  Project: Kotoba");
510        println!("📝 Description: GP2-based Graph Rewriting Language");
511        println!("🏗️  Architecture: Process Network Graph Model");
512        println!("🔧 Version: {}", env!("CARGO_PKG_VERSION"));
513
514        if detailed {
515            println!("\n📊 Detailed Information:");
516            println!("✅ Core Features:");
517            println!("  - ISO GQL compliant queries");
518            println!("  - MVCC + Merkle persistent storage");
519            println!("  - Distributed execution");
520            println!("  - Graph rewriting with DPO rules");
521            println!("  - Jsonnet-based configuration");
522            println!("  - Web framework integration");
523            println!("  - Deploy system (under development)");
524        }
525
526        if json {
527            println!("\n📄 JSON Output:");
528            println!("{{");
529            println!("  \"name\": \"Kotoba\",");
530            println!("  \"version\": \"{}\",", env!("CARGO_PKG_VERSION"));
531            println!("  \"description\": \"GP2-based Graph Rewriting Language\"");
532            println!("}}");
533        }
534
535        Ok(())
536    }
537
538    async fn run_task(&self, task: Option<String>, file: Option<PathBuf>, list: bool) -> kotoba_core::types::Result<()> {
539        if list {
540            println!("📋 Available tasks:");
541            println!("💡 Task listing not yet implemented");
542        } else if let Some(task_name) = task {
543            println!("📋 Running task: {}", task_name);
544            if let Some(f) = &file {
545                println!("📁 From file: {}", f.display());
546            }
547            println!("💡 Jsonnet task execution not yet implemented");
548        } else {
549            println!("📋 Running default task...");
550            println!("💡 Task execution not yet implemented");
551        }
552        Ok(())
553    }
554
555    async fn run_repl(&self, history: Option<PathBuf>, graph: Option<PathBuf>) -> kotoba_core::types::Result<()> {
556        println!("💻 Starting Kotoba GQL REPL");
557        if let Some(h) = &history {
558            println!("📚 History file: {}", h.display());
559        }
560        if let Some(g) = &graph {
561            println!("📊 Initial graph: {}", g.display());
562        }
563        println!("💡 Interactive GQL REPL not yet implemented");
564        println!("💡 Type 'exit' or Ctrl+C to quit");
565        Ok(())
566    }
567
568    async fn run_compile(&self, input: PathBuf, output: Option<PathBuf>, target: String, optimize: u8) -> kotoba_core::types::Result<()> {
569        println!("⚙️  Compiling: {}", input.display());
570        if let Some(out) = &output {
571            println!("📤 Output: {}", out.display());
572        }
573        println!("🎯 Target: {}", target);
574        println!("⚡ Optimization level: {}", optimize);
575        println!("💡 Compilation not yet implemented");
576        Ok(())
577    }
578
579    async fn run_generate(&self, generator: GeneratorType, schema: Option<PathBuf>, output: Option<PathBuf>, lang: String) -> kotoba_core::types::Result<()> {
580        match generator {
581            GeneratorType::Types => println!("🛠️  Generating TypeScript types..."),
582            GeneratorType::Client => println!("🛠️  Generating GraphQL client..."),
583            GeneratorType::Server => println!("🛠️  Generating server stubs..."),
584            GeneratorType::Docs => println!("🛠️  Generating documentation..."),
585        }
586
587        if let Some(s) = &schema {
588            println!("📋 Schema: {}", s.display());
589        }
590        if let Some(out) = &output {
591            println!("📁 Output directory: {}", out.display());
592        }
593        println!("🔤 Language: {}", lang);
594        println!("💡 Code generation not yet implemented");
595        Ok(())
596    }
597
598    #[cfg(feature = "deploy")]
599    async fn run_deploy(&self, _command: DeployCommands) -> kotoba_core::types::Result<()> {
600        println!("🚀 Deploy command (under development)...");
601        println!("💡 Use 'kotoba deploy --help' for available subcommands");
602        Ok(())
603    }
604
605    async fn run_server(&self, port: u16, host: String, config: Option<PathBuf>, tls: bool, _cert: Option<PathBuf>, _key: Option<PathBuf>) -> kotoba_core::types::Result<()> {
606        println!("🌐 Starting Kotoba HTTP Server");
607        println!("=============================");
608        println!("🏠 Host: {}", host);
609        println!("🔌 Port: {}", port);
610        println!("🔒 TLS: {}", if tls { "Enabled" } else { "Disabled" });
611
612        if let Some(cfg) = &config {
613            println!("⚙️  Config: {}", cfg.display());
614        }
615
616        println!("💡 HTTP server not yet implemented");
617        println!("💡 Server would be available at: http{}://{}:{}",
618                 if tls { "s" } else { "" }, host, port);
619        Ok(())
620    }
621
622    #[cfg(feature = "deploy")]
623    async fn run_cache(&self, command: CacheCommands) -> kotoba_core::types::Result<()> {
624        println!("💾 Kotoba Cache Management");
625        match command {
626            CacheCommands::Clear => {
627                println!("🧹 Clearing all caches...");
628                println!("✅ Cache cleared successfully");
629            }
630            CacheCommands::Info => {
631                println!("📊 Cache Information:");
632                println!("💾 Cache directory: ~/.cache/kotoba");
633                println!("📦 Cache size: Not implemented");
634                println!("📅 Last updated: Not implemented");
635            }
636            CacheCommands::Dir => {
637                println!("📁 Cache directory: ~/.cache/kotoba");
638            }
639        }
640        Ok(())
641    }
642
643    async fn run_doc(&self, input: Option<PathBuf>, output: PathBuf, format: String, open: bool) -> kotoba_core::types::Result<()> {
644        println!("📚 Generating Documentation");
645        println!("==========================");
646
647        if let Some(inp) = &input {
648            println!("📥 Input: {}", inp.display());
649        } else {
650            println!("📥 Input: Auto-detecting files...");
651        }
652
653        println!("📤 Output: {}", output.display());
654        println!("📄 Format: {}", format);
655
656        if open {
657            println!("🌐 Will open in browser after generation");
658        }
659
660        println!("💡 Documentation generation not yet implemented");
661        Ok(())
662    }
663
664    async fn run_init(&self, name: Option<String>, template: String, force: bool) -> kotoba_core::types::Result<()> {
665        println!("🎯 Initializing New Kotoba Project");
666        println!("=================================");
667
668        let project_name = name.unwrap_or_else(|| "my-kotoba-project".to_string());
669        println!("🏷️  Project name: {}", project_name);
670        println!("📋 Template: {}", template);
671
672        if force {
673            println!("⚠️  Force mode enabled - will overwrite existing files");
674        }
675
676        println!("💡 Project templates available:");
677        println!("  - basic: Basic Kotoba project");
678        println!("  - web: Web application with HTTP server");
679        println!("  - api: GraphQL API server");
680        println!("  - fullstack: Full-stack application");
681        println!("💡 Project initialization not yet implemented");
682        Ok(())
683    }
684
685    fn show_version(&self) {
686        println!("Kotoba {}", env!("CARGO_PKG_VERSION"));
687        println!("Graph processing system inspired by Deno");
688    }
689}
690
691/// CLIのメイン実行関数
692pub async fn run_cli() -> kotoba_core::types::Result<()> {
693    let cli = Cli::parse();
694
695    let runner = CliRunner::new();
696    runner.run(cli).await
697}