123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2020-2022 Nomadic Labs <contact@nomadic-labs.com> *)(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)openBase(* The expected output of a normal run of Tezt is the log of the tests.
So these should be on stdout.
However, for some commands (especially those that are expected to be parsed
by scripts such as --list-tsv), the expected output contains no logs, only data.
For those commands, we thus log to stderr instead. We don't expect much logs
except maybe warnings like "leftover files from a previous run". *)letchannel=(* The use of a pattern with all fields ensures that we will update this if we
add new commands that should log to stderr. *)let{Cli.color=_;log_level=_;log_file=_;log_buffer_size=_;commands=_;temporary_file_mode=_;keep_going=_;files_to_run=_;tests_to_run=_;tests_not_to_run=_;patterns_to_run=_;tags_to_run=_;tags_not_to_run=_;list;global_timeout=_;retry=_;test_timeout=_;reset_regressions=_;on_unknown_regression_files_mode=_;loop_mode=_;time=_;starting_port=_;record=_;from_records=_;resume_file=_;resume=_;job=_;job_count=_;suggest_jobs;junit=_;skip=_;only=_;test_args=_;}=Cli.optionsinif(matchlistwithNone->false|Some(`Ascii_art|`Tsv)->true)||suggest_jobsthenstderrelsestdout(* In theory we could simply escape spaces, backslashes, double quotes, single quotes
and other symbols with a meaning for the shell.
But 'some long argument' is arguably more readable than some\ long\ argument.
We use this quoting method if the string contains no single quote. *)letquote_shells=letcontains_single_quote=reffalseinletneeds_quotes=reffalseinletcategorize=function|'\''->needs_quotes:=true;contains_single_quote:=true|'a'..'z'|'A'..'Z'|'0'..'9'|'-'|'_'|'.'|'+'|'/'|':'|'@'|'%'->()|_->needs_quotes:=trueinString.itercategorizes;ifnot!needs_quotesthenselseifnot!contains_single_quotethen"'"^s^"'"elseFilename.quotesletquote_shell_commandcommandarguments=String.concat" "(List.mapquote_shell(command::arguments))moduleColor=structtypet=stringlet(++)=(^)letreset="\027[0m"letbold="\027[1m"letapplycolorstring=ifCli.options.colorthencolor^string^resetelsestringmoduleFG=structletblack="\027[30m"letred="\027[31m"letgreen="\027[32m"letyellow="\027[33m"letblue="\027[34m"letmagenta="\027[35m"letcyan="\027[36m"letgray="\027[37m"letbright_white="\027[97m"endmoduleBG=structletblack="\027[40m"letred="\027[41m"letgreen="\027[42m"letyellow="\027[43m"letblue="\027[44m"letmagenta="\027[45m"letcyan="\027[46m"letgray="\027[47m"letbright_white="\027[107m"endend(* The log buffer is a queue with a maximum size.
Older items are dropped. *)moduleLog_buffer=structletcapacity=Cli.options.log_buffer_size(* Each item is a tuple [(timestamp, color, prefix, prefix_color, progress, message)]. *)letbuffer=Array.makecapacity(0.,None,None,None,None,"")(* Index where to add the next item. *)letnext=ref0(* Number of items which are actually used in the array. *)letused=ref0letreset()=next:=0;used:=0letpushline=ifcapacity>0then(if!next>=capacitythennext:=0;buffer.(!next)<-line;incrnext;used:=mincapacity(!used+1))(* Note: don't call [push] in [f]. *)letiterf=letfirst=!next-!usedinletlast=!next-1infori=firsttolastdo(* Add [capacity] to avoid issues with modulo of negative integers. *)fbuffer.((i+capacity)modcapacity)doneendletoutput_timestampoutputtimestamp=lettime=Unix.gmtimetimestampinoutput(Printf.sprintf"%02d:%02d:%02d.%03d"time.tm_hourtime.tm_mintime.tm_sec(int_of_float((timestamp-.float(truncatetimestamp))*.1000.)))letlog_line_to~use_colors(timestamp,color,prefix,prefix_color,progress,message)channel=letoutput=output_stringchannelinoutput"[";output_timestampoutputtimestamp;output"] ";ifuse_colorsthenOption.iteroutputcolor;Option.iter(funprefix->output"[";ifuse_colorsthenOption.iteroutputprefix_color;outputprefix;(ifuse_colorsthenmatchprefix_colorwith|None->()|Some_->outputColor.reset;Option.iteroutputcolor);output"] ")prefix;Option.iteroutputprogress;outputmessage;ifuse_colors&&color<>NonethenoutputColor.reset;output"\n"letlog_string~(level:Cli.log_level)?color?prefix?prefix_color?progress_msgmessage=matchString.split_on_char'\n'messagewith|[]|[""]->()|lines->letlog_linemessage=letline=(Unix.gettimeofday(),color,prefix,prefix_color,progress_msg,message)inOption.iter(log_line_to~use_colors:falseline)Cli.options.log_file;match(Cli.options.log_level,level)with|_,Quiet->invalid_arg"Log.log_string: level cannot be Quiet"|Error,Error|Warn,(Error|Warn)|Report,(Error|Warn|Report)|Info,(Error|Warn|Report|Info)|Debug,(Error|Warn|Report|Info|Debug)->(iflevel=ErrorthenLog_buffer.iter@@funline->log_line_to~use_colors:Cli.options.colorlinechannel);Log_buffer.reset();log_line_to~use_colors:Cli.options.colorlinechannel;flushchannel|(Quiet|Error|Warn|Report|Info),_->Log_buffer.pushlineinList.iterlog_linelinesletlog~level?color?prefixfmt=Format.kasprintf(log_string~level?color?prefix)fmtletdebug?color=log~level:Debug?colorletinfo?color=log~level:Info?colorletreport?color=log~level:Report?colorletwarnx=log~level:Warn~color:Color.FG.red~prefix:"warn"xleterrorx=log~level:Error~color:Color.FG.red~prefix:"error"xtypetest_result=Successful|Failedofstring|Abortedlettest_result~test_index~test_count~failure_count~iterationtest_resulttest_name=letprefix,prefix_color=matchtest_resultwith|Successful->("SUCCESS",Color.(FG.green++bold))|Failed_->("FAILURE",Color.(FG.red++bold))|Aborted->("ABORTED",Color.(FG.red++bold))inletmessage=ifCli.options.loop_mode<>Count1thenPrintf.sprintf"(loop %d) %s"iterationtest_nameelsetest_nameinletprogress_msg=sf"(%d/%d%s) "test_indextest_count(iffailure_count>0thensf", %d failed"failure_countelse"")inlog_string~level:Report~prefix~prefix_color~progress_msgmessageletcommand?color?prefixcommandarguments=letmessage=quote_shell_commandcommandargumentsinlog_string~level:Debug?color?prefixmessage;ifCli.options.commandsthenprint_endlinemessage