~otheb/kb

ref: cacd6f6834838861b4aead9613f3c2c14f1613c1 kb/kb/main.d -rw-r--r-- 11.0 KiB View raw
cacd6f68Olie Ayre Fixed typo in usage for CLI 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
module main ;

import std.algorithm ;
import std.stdio     ;
import std.conv      ;
import std.array     ;
import std.string    ;
import std.socket    ;
import std.typecons  ;
import std.json      ;
import std.process   ;
import std.path      ;
import std.file      ;

import arsd.http2 ;

int usage() {
	writeln(
"Usage: kb <host> <command> [command-args...]\n
\thost: hostname/IP/port of API server e.g. 'myapiserver:8000'
\tcommands:\n
\tls [-r] : list entries by ID (or by timestamp if `-r` is provided).
\tview ID : view entry #ID in $PAGER (defaults to `less -r`).
\tnew     : create a new entry in $EDITOR (defaults to `vim`).
\tedit ID : edit entry #ID in $EDITOR.
\trm ID   : delete entry #ID.
\tsearch TERMS... :
\t    search based on provided terms and display results in $PAGER." ) ;
	return 1 ;
}

const string entryfooter = q"EOS

# Please enter your description for the knowledge base. Lines starting with '#'
# will be ignored, and an empty message or title will abort the entry creation.
#
# The first line (starting with 'Title:') is for the title of your entry, which
# you should append to the line. The 'Tags:' line is for tagging your entry with
# key words to make it easier to find. These should be separated with
# whitespace. The 'Deprecated:' line is for showing whether or not the entry is
# to be considered old, deprecated, or no longer relevant. A value of "yes" or
# "true" will mark it as such, and any other value will be treated as "no" in
# that the entry is relevant. The 'IsPatch:' line marks whether edits to an
# existing entry are to be treated as a new version ("no"/"false") or as a patch
# to the current version ("yes"/"true"/*) e.g. if you're just fixing typos. An
# example set of headers might be:
#
# Title: My entry title
# Tags: first second third
# Deprecated: no
# IsPatch: no
# My content here...
EOS" ;

string HOST   = "127.0.0.1" ;
ushort PORT   = 80          ;
string PAGER  = "less -r"   ;
string EDITOR = "vim"       ;

int main( string[] args ) {
	if ( args.length < 3 ) { return usage() ; }

	{ // set host and port
		string[] hp = args[1].split( ":" ) ;
		HOST = hp[0] ;
		if ( hp.length > 1 ) { PORT = hp[1].to!ushort ; }
	}

	// main command
	try switch ( args[2] ) {
	case "ls" :
		if ( args.length == 4 && args[3] == "-r" ) { ls( true ) ;
		} else if ( args.length == 3 ) { ls( false ) ;
		} else { return usage() ; }
		break ;
	case "view" :
		if ( args.length == 4 && args[3].tr( "0-9" , "" , "d" ).length == 0 ) {
			view( args[3] ) ;
		} else { return usage() ; }
		break ;
	case "new" :
		if ( args.length == 3 ) { new_() ;
		} else { return usage() ; }
		break ;
	case "edit" :
		if ( args.length == 4 && args[3].tr( "0-9" , "" , "d" ).length == 0 ) {
			edit( args[3] ) ;
		} else { return usage() ; }
		break ;
	case "rm" :
		if ( args.length == 4 && args[3].tr( "0-9" , "" , "d" ).length == 0 ) {
			rm( args[3] ) ;
		} else { return usage() ; }
		break ;
	case "search" :
		if ( args.length > 3 ) { search( args[3..$] ) ;
		} else { return usage() ; }
		break ;
	default : return usage() ;
	} catch ( SocketOSException e ) {
		writeln( "No connection to API server at " , url ) ;
		return 1 ;
	}

	return 0 ;
}

string url() { return "http://" ~ HOST ~ ":" ~ PORT.to!string ; }
string tmp() { return buildPath( tempDir() , "kb-tempbuffer" ) ; }

auto index() { return get( url ~ "/" ).waitForCompletion() ; }
auto entry( long id ) {
	return get( url ~ "/" ~ id.to!string ).waitForCompletion() ;
}
auto entry( string id ) { return get( url ~ "/" ~ id ).waitForCompletion() ; }
auto post( string j , string id = "" ) {
	auto client = new HttpClient() ;
	return client.request( Uri( url ~ "/" ~ id ) , HttpVerb.POST ,
	                       cast(ubyte[])j , "application/json" )
	       .waitForCompletion() ;
}
auto patch( string j , string id ) {
	auto client = new HttpClient() ;
	return client.request( Uri( url ~ "/" ~ id ) , HttpVerb.PATCH ,
	                       cast(ubyte[])j , "application/json" )
	       .waitForCompletion() ;
}
auto delete_( string id ) {
	auto client = new HttpClient() ;
	return client.request( Uri( url ~ "/" ~ id ) , HttpVerb.DELETE )
	       .waitForCompletion() ;
}

void ls( bool recent ) {
	auto res = index() ;
	if ( res.code != 200 ) {
		writeln( "Error " , res.code ) ;
		return ;
	}
	auto pipe = pipeProcess( PAGER.split() , Redirect.stdin ) ;
	pipe.stdin.write(
		res.contentText.parseJSON()["ids"].array.map!( e => entry( e.integer ) )
		.filter!( r => r.code == 200 ).map!( r => r.contentText.parseJSON() )
		.array.sort!( ( a , b ) =>
			recent ? a["time"].integer > b["time"].integer :
				a["id"].integer < b["id"].integer
		).map!( e => e.fmtshort() ).join( "\n" )
	) ;
	pipe.stdin.close() ;
	pipe.pid.wait() ;
}

string fmtdate( long ts ) {
	import std.datetime ;
	auto dt = cast(DateTime)SysTime.fromUnixTime( ts , LocalTime() ) ;
	return text ( // D Month YEAR @ HH:MMap
		dt.day , " " , // day
		[ "" , "January" , "February" , "March" , "April" , "May" , "June" ,
		  "July" , "August" , "September" , "October" , "November" , "December"
		][ dt.month ] , " " , // month
		dt.year , " @ " , // year
		dt.hour % 12 == 0 ? 12 : dt.hour % 12 , ":" , // hour
		std.conv.to!string( dt.minute ).rightJustify( 2 , '0' ) , // minute
		dt.hour >= 12 ? "pm" : "am" // am/pm
	) ;
}

string fmtshort( JSONValue j ) {
	return text(
		"#" , j["id"].integer , // #ID
		j["old"].boolean ? " [DEPRECATED] " : " " , // deprecated
		j["title"].str , "\n\t" , // title
		j["time"].integer.fmtdate() , // date and time
		j["tags"].array.length == 0 ? "" : "\n\t" ~
			j["tags"].array.map!( t => "[" ~ t.str ~ "]" ).array.join( " " )
	) ;
}

string fmtlong( JSONValue j ) {
	return text(
		j.fmtshort() , "\n" , // short form at start
		j["content"].str.wrap( 80 ) , // content
		j["history"].array.length == 0 ? "" :
		"\nHistory:\n" ~ // history header
		j["history"].array.map!( h => text(
			"\n\t" , h["time"].integer.fmtdate() , "\n" , // date and time
			h["content"].str.wrap( 80 ) // content
		) ).join( "" )
	) ;
}

void view( string id ) {
	auto res = get( url ~ "/" ~ id ).waitForCompletion() ;
	if ( res.code == 404 ) {
		writeln( "Entry " , id , " does not exist" ) ;
	} else if ( res.code != 200 ) {
		writeln( "Error " , res.code ) ;
	} else {
		auto pipe = pipeProcess( PAGER.split() , Redirect.stdin ) ;
		pipe.stdin.write( res.contentText.parseJSON().fmtlong() ) ;
		pipe.stdin.close() ;
		pipe.pid.wait() ;
	}
}

void submit( string id = "" ) {
	// if id != "" then we're editing so get the existing entry
	auto e = JSONValue() ;
	if ( id != "" ) {
		// get existing entry
		auto res = entry( id ) ;
		if ( res.code == 404 ) {
			writeln( "Entry " , id , " doesn't exist" ) ;
			return ;
		} else if ( res.code == 304 ) {
			writeln( "New version is identical to exsiting" ) ;
			return ;
		} else if ( res.code != 200 ) {
			writeln( "Error " , res.code ) ;
			return ;
		}
		e = res.contentText.parseJSON() ;
	}

	// create the temporary file
	std.file.write( tmp , e.type == JSONType.null_ ? mktemplate() :
	                mktemplate( e ) ) ;

	// edit in $EDITOR
	spawnProcess( EDITOR.split() ~ tmp ).wait() ;

	// parse the file then remove it
	auto j = tmp.readText().parsefile() ;
	remove( tmp ) ;

	// abort on empty content/title
	if ( j.type == JSONType.null_ ) {
		writeln( "Aborting on empty content/title" ) ;
		return ;
	}

	// submit
	if ( id == "" ) {
		// new
		auto res = post( j.toString() ) ;
		if ( res.code != 200 ) {
			writeln( "Error " , res.code ) ;
		} else {
			writeln( "Created new entry #" ,
			         res.contentText.parseJSON()["id"].integer , " '" ,
			         j["title"].str , "'" ) ;
		}
	} else {
		auto res = j["ispatch"].boolean ?
			patch( j.toString() , id ) :
			post ( j.toString() , id ) ;
		if ( res.code != 200 ) {
			writeln( "Error " , res.code ) ;
		} else {
			writeln( "Updated entry #" ,
			         res.contentText.parseJSON()["id"].integer , " '" ,
			         j["title"].str , "'" ) ;
		}
	}
}

void new_() { submit() ; }

string mktemplate() {
	return "Title:\nTags:\nDeprecated: no\n\n" ~ entryfooter ;
}

string mktemplate( JSONValue j ) {
	return text(
		"Title: " , j["title"].str , "\n" , // title
		"Tags: " ,
		j["tags"].array.map!( t => t.str ).join( " " ) , "\n" , // tags
		"Deprecated: " , j["old"].boolean ? "yes" : "no" , "\n" , // deprecated
		"IsPatch: \n" , // is a patch
		j["content"].str , "\n" , // content
		entryfooter // stock content at the bottom
	) ;
}

auto parsefile( string content ) {
	// strip comments
	string[] lines = content.splitLines.filter!( l => ! l.startsWith( "#" ) )
	                 .array ;
	string title ; {
		auto i = lines.countUntil!( l => l.startsWith( "Title:" ) ) ;
		// return null json if there's no title
		if ( i == -1 ) { return JSONValue() ;
		} else {
			title = lines[i][ "Title:".length .. $ ].strip() ;
			lines.remove( i ) ;
		}
		// return null json if the title is empty
		if ( title == "" ) { return JSONValue() ; }
	}
	string[] tags ; {
		auto i = lines.countUntil!( l => l.startsWith( "Tags:" ) ) ;
		if ( i != -1 ) {
			tags = lines[i][ "Tags:".length .. $ ].split()
			       .filter!( t => t != "" ).map!( t => t.toLower() ).array ;
			lines.remove( i ) ;
		}
	}
	bool ispatch ; {
		auto i = lines.countUntil!( l => l.startsWith( "IsPatch:" ) ) ;
		if ( i == -1 ) { ispatch = false ;
		} else {
			ispatch = [ "yes" , "true" ]
			          .canFind( lines[i][ "IsPatch:".length .. $ ].strip()
			                    .toLower() ) ;
			lines.remove( i ) ;
		}
	}
	bool old ; {
		auto i = lines.countUntil!( l => l.startsWith( "Deprecated:" ) ) ;
		if ( i == -1 ) { old = false ;
		} else {
			old = [ "yes" , "true" ]
				.canFind( lines[i][ "Deprecated:".length .. $ ].strip()
				          .toLower() ) ;
			lines.remove( i ) ;
		}
	}
	string body = lines.join( "\n" ).strip() ;
	return body == "" ? JSONValue() : JSONValue( [
		"title"   : JSONValue( title   ) ,
		"tags"    : JSONValue( tags    ) ,
		"old"     : JSONValue( old     ) ,
		"content" : JSONValue( body    ) ,
		"ispatch" : JSONValue( ispatch )
	] ) ;
}

void edit( string id ) { submit( id ) ; }

void rm( string id ) {
	auto res = delete_( id ) ;
	if ( res.code == 404 ) { writeln( "Entry " , id , " doesn't exist" ) ;
	} else if ( res.code != 200 ) { writeln( "Error " , res.code ) ;
	} else { writeln( "Deleted entry " , id ) ; }
}

void search( string[] terms ) {
	writeln( "searching entries based on search terms " , terms ,
	         " and displaying results in " , PAGER ) ;
	// make the request
	auto client = new HttpClient() ;
	auto res = client.request( Uri( url ~ "/s" ) , HttpVerb.POST ,
		cast(ubyte[])JSONValue( [
			"search" : JSONValue( terms.join( " " ) )
		] ).toString() , "application/json" ).waitForCompletion() ;
	if ( res.code != 200 ) { writeln( "Error " , res.code ) ;
	} else {
		auto pipe = pipeProcess( PAGER.split() , Redirect.stdin ) ;
		pipe.stdin.writeln(
			res.contentText.parseJSON()["results"].array
			.map!( r => tuple( r["id"].integer , r["relevance"].integer ) )
			.array.sort!( ( a , b ) => a[1] > b[1] ).map!( r => entry( r[0] ) )
			.filter!( r => r.code == 200 )
			.map!( r => r.contentText.parseJSON() ).map!( e => e.fmtshort() )
			.join( "\n" )
		) ;
		pipe.stdin.close() ;
		pipe.pid.wait() ;
	}
}