@@ -20,6 +20,8 @@ defmodule GitWork.CLI do
2020 }
2121
2222 def run ( args ) do
23+ { format , args } = extract_format ( args )
24+
2325 case args do
2426 [ "--help" ] ->
2527 print_help ( )
@@ -37,42 +39,63 @@ defmodule GitWork.CLI do
3739 if "--help" in rest or "-h" in rest do
3840 print_command_help ( command )
3941 else
40- dispatch ( command , rest )
42+ dispatch ( command , rest , format )
4143 end
4244
4345 [ ] ->
4446 print_help ( )
4547 end
4648 end
4749
48- defp dispatch ( command , args ) do
50+ defp extract_format ( args ) do
51+ case Enum . split_with ( args , & ( & 1 == "--format=json" ) ) do
52+ { format_args , rest } when format_args != [ ] ->
53+ { :json , rest }
54+
55+ _ ->
56+ { :text , args }
57+ end
58+ end
59+
60+ defp dispatch ( command , args , format ) do
4961 case Map . get ( @ commands , command ) do
5062 nil ->
51- IO . write ( :stderr , "git-work: unknown command '#{ command } '\n \n " )
63+ GitWork.Output . print_error ( " unknown command '#{ command } '" , format )
5264 print_help ( )
5365 System . halt ( 1 )
5466
5567 module ->
5668 result =
5769 try do
58- module . run ( args )
70+ module . run ( args , format )
5971 rescue
6072 e ->
6173 { :error , "unexpected error: #{ Exception . message ( e ) } " }
6274 end
6375
64- handle_result ( result )
76+ handle_result ( result , format )
6577 end
6678 end
6779
68- defp handle_result ( { :ok , output } ) when is_binary ( output ) and output != "" do
69- IO . puts ( output )
80+ defp handle_result ( { :ok , % GitWork.Output { } = output } , format ) do
81+ GitWork.Output . print ( output , format )
82+ end
83+
84+ defp handle_result ( { :ok , output } , format ) when is_binary ( output ) and output != "" do
85+ case format do
86+ :json ->
87+ json = JSON . encode! ( % { path: output , messages: [ ] } )
88+ IO . write ( :stderr , json <> "\n " )
89+
90+ :text ->
91+ IO . puts ( output )
92+ end
7093 end
7194
72- defp handle_result ( { :ok , _ } ) , do: :ok
95+ defp handle_result ( { :ok , _ } , _format ) , do: :ok
7396
74- defp handle_result ( { :error , message } ) do
75- IO . write ( :stderr , "git-work: #{ message } \n " )
97+ defp handle_result ( { :error , message } , format ) do
98+ GitWork.Output . print_error ( message , format )
7699 System . halt ( 1 )
77100 end
78101
@@ -89,7 +112,7 @@ defmodule GitWork.CLI do
89112
90113 defp print_help do
91114 IO . write ( :stderr , """
92- usage: git-work <command> [<args>]
115+ usage: git-work [--format=json] <command> [<args>]
93116
94117 Commands:
95118 activate <shell> Print shell integration (bash, zsh, fish)
@@ -100,8 +123,9 @@ defmodule GitWork.CLI do
100123 sync (s) [--dry-run] Fetch and prune stale worktrees
101124 list (ls) List all worktrees
102125
103- Options:
104- --help Show this help
126+ Global options:
127+ --format=json Output results as JSON to stderr
128+ --help Show this help
105129
106130 Run 'git-work <command> --help' for more information on a specific command.
107131 """ )
0 commit comments