You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 4 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 5 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 4 година
пре 6 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 6 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 4 година
пре 3 година
пре 4 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 4 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 4 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 5 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 5 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 6 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343
  1. global.env = process.env
  2. global.env.NODE_ENV = global.env.NODE_ENV || 'development'
  3. const fs = require('fs')
  4. var path = require('path');
  5. var utils = require('bbhverse');
  6. var any = utils.any;
  7. var Tasq = utils.Tasq
  8. var statuslog = utils.Traq
  9. var Traq = utils.Traq
  10. Tasq.addlistener(statuslog.statuslog)
  11. fs.writeFileSync('run.log', ', ' + JSON.stringify( { m : 'Hello'} ), { 'flag': 'a+' })
  12. Tasq.addlistener((e)=>{ fs.writeFileSync('run.log', ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  13. var cli = require('./cliverse')
  14. function isWin(){ return /^win/.test(process.platform) }
  15. if(isWin()) {
  16. var win_verse = require('./win_verse')
  17. var shell_verse = win_verse;
  18. }
  19. else {
  20. var lin_verse = require('./lin_verse')
  21. var shell_verse = lin_verse;
  22. }
  23. var nodeShellExec = cli.nodeShellExec;
  24. var chalk = require('chalk')
  25. const homedir = require('os').homedir();
  26. function sysAddPathVar(addpath){
  27. // Object.assign({
  28. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  29. // }, options)
  30. // powershell $env:Path -split ';'
  31. var etask = ()=>{
  32. return nodeShellExec('Powershell.exe', [
  33. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  34. $newpath = $path + ';${addpath}'
  35. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  36. ]).then(() => {
  37. fs.writeFileSync('run.done', 'success')
  38. }).catch(() => {
  39. fs.writeFileSync('run.done', 'error')
  40. })
  41. }
  42. etask.statuslog = statuslog
  43. etask.selectedinstance = selectedinstance
  44. etask.processedArgs = processedArgs
  45. etask.runtimestamp = runtimestamp
  46. etask.ENV = ENV
  47. return shell_verse.runElevated(etask)
  48. // var newpath = addpath.split(';');
  49. // newpath.push(addpath)
  50. // newpath = Array.from(new Set(newpath)).join(';')
  51. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  52. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  53. // // %AppData%\npm
  54. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  55. }
  56. // singleton one time lazy
  57. var getCredentials = function(){
  58. // First call
  59. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  60. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  61. console.log(creds);
  62. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  63. // Subsequent calls
  64. getCredentials = ()=>{ return creds }
  65. return getCredentials();
  66. }
  67. function getCurrentFolder(){
  68. var tasks = [
  69. // () => {
  70. // // Use junctions to avoid npm package issues
  71. // var p = nodeShellExec('cd').then((result)=>{
  72. // console.dir(result)
  73. // }).catch((e) => { console.error(e) })
  74. // return p;
  75. // }
  76. ()=>{
  77. return Promise.resolve(process.cwd())
  78. }
  79. ];
  80. return any(tasks);
  81. }
  82. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  83. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  84. const runtimestamp = (new Date()).getTime();
  85. function getVersion() { return BUILD_VERSION; }
  86. console.log(getVersion());
  87. // 'use strict';
  88. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  89. // PB : TODO --
  90. // runas bypass non elevated tasks when we request privelege
  91. // runas message is always error needs to be fixed.
  92. // runas wait needs to be parallelized.
  93. // suppress elevation check error messages
  94. // support runas lauched directly from shell.
  95. // pass in environment in hta to shellexecute.
  96. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  97. (function () {
  98. "use strict";
  99. if (!Array.prototype.earlyreduce) {
  100. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  101. var iterable = this;
  102. var donecallback = donecallback || (a=>a)
  103. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  104. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  105. // function *earlyReduceGenerator(acc, v, i, a) {
  106. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  107. var element = iterable[i]
  108. result = eachcallback(result, element, i, iterable)
  109. if(result.done) return donecallback(result)
  110. }
  111. // }
  112. return donecallback(result)
  113. }
  114. }
  115. }());
  116. const { existsSync } = require('fs');
  117. const existslink = function(name, cb){
  118. fs.lstat(name, (error, stats) => {
  119. if (error) {
  120. console.log(error);
  121. cb(error)
  122. }
  123. else {
  124. console.log("Stats object for: example_directory.txt");
  125. console.log(stats);
  126. // Using methods of the Stats object
  127. console.log("Path is file:", stats.isFile());
  128. console.log("Path is directory:", stats.isDirectory());
  129. cb(null, true)
  130. }
  131. });
  132. }
  133. const existsFolderSync = existsSync;
  134. const cliargs = utils.cliargs;
  135. const processedArgs = cliargs(process.argv.slice(2));
  136. if(!processedArgs.wd){
  137. if(process.env.wd){
  138. }
  139. else {
  140. process.env.wd = process.cwd();
  141. if(process.cwd() === __dirname) {
  142. // This script was launched in the same dir.
  143. // We do not know if it was copied to some random location. Check if we have elxr installed in current location. Or subidr.
  144. process.env.wd = path.dirname( process.env.wd ); // Default to the parent.
  145. }
  146. }
  147. }
  148. else process.env.wd = processedArgs.wd
  149. var ENV = Object.assign({}, process.env); // Shallow clone it.
  150. console.dir(processedArgs)
  151. // PB : TODO -- defaults for valuless arguments if passed.
  152. // Object.keys(processedArgs).forEach(a=>{
  153. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  154. // }
  155. // })
  156. //
  157. // Object.keys(clioverrides).forEach( prop => { })
  158. var globSync = require('glob').sync;
  159. const { readdir } = require("fs").promises
  160. // Directory shallow walk and do perform on each dir.
  161. const dirs = async (perform, path) => {
  162. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  163. if (dir.isDirectory()) perform(dir)
  164. }
  165. }
  166. var templateprocess = function(str, substitutes){
  167. const regex = /__(.*?)__/gm;
  168. // const str = `__link____instance__server-lib__name__`;
  169. let m;
  170. return str.replace(regex, function(match, key) {
  171. console.log(`Found match, group ${match}: ${key}`);
  172. return substitutes[key] || match;
  173. })
  174. // while ((m = regex.exec(str)) !== null) {
  175. // // This is necessary to avoid infinite loops with zero-width matches
  176. // if (m.index === regex.lastIndex) {
  177. // regex.lastIndex++;
  178. // }
  179. // var rstr = str;
  180. // // The result can be accessed through the `m`-variable.
  181. // m.forEach((match, groupIndex) => {
  182. // // rstr = rstr.replace( groupIndex
  183. // console.log(`Found match, group ${groupIndex}: ${match}`);
  184. // if(groupIndex === 0) return
  185. // });
  186. // }
  187. }
  188. function copyFileSync( source, target , options) {
  189. var targetFile = target;
  190. // If target is a directory, a new file with the same name will be created
  191. if ( fs.existsSync( target ) ) {
  192. if ( fs.lstatSync( target ).isDirectory() ) {
  193. targetFile = path.join( target, path.basename( source ) );
  194. }
  195. }
  196. fs.writeFileSync(targetFile, fs.readFileSync(source));
  197. }
  198. function copyFolderRecursiveSync( source, target, options ) {
  199. var files = [];
  200. // Check if folder needs to be created or integrated
  201. var targetFolder = path.join( target, path.basename( source ) );
  202. if ( !fs.existsSync( targetFolder ) ) {
  203. fs.mkdirSync( targetFolder );
  204. }
  205. // Copy
  206. if ( fs.lstatSync( source ).isDirectory() ) {
  207. files = fs.readdirSync( source );
  208. files.forEach( function ( file ) {
  209. var curSource = path.join( source, file );
  210. if ( fs.lstatSync( curSource ).isDirectory() ) {
  211. copyFolderRecursiveSync( curSource, targetFolder );
  212. } else {
  213. copyFileSync( curSource, targetFolder );
  214. }
  215. } );
  216. }
  217. }
  218. var getShellTask = (command, args, options) => {
  219. options = options || {}
  220. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  221. return () => {
  222. var p = callshell( [command, args, Object.assign({
  223. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  224. }, options)
  225. ])()
  226. if (options.ignorefailures) {
  227. return p.catch(e => {
  228. // Ignore. Not a major error.
  229. })
  230. }
  231. else return p;
  232. }
  233. }
  234. var callshelltask = (args) => {
  235. // console.dir(args)
  236. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  237. return args;
  238. }
  239. return getshelltask(args)()
  240. }
  241. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  242. var getshelltask = (args) => {
  243. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  244. var getgitbashtask = (args, onEachError) => { return () => {
  245. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  246. }
  247. var getTaskCheckExists = shell_verse.getTaskCheckExists
  248. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  249. // var getTaskWithoutElevation = function(tasdef){
  250. // return ()=>{
  251. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  252. // else Promise.resolve(true)
  253. // }
  254. // }
  255. var gitops = {
  256. getdiscoverbranchcmd : function(repo){
  257. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  258. var cmd = [gitbash
  259. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  260. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  261. return cmd
  262. }
  263. }
  264. var getPullCmd = (repo, branch) => {
  265. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  266. // console.log(useGitPull)
  267. var pullCmd = []
  268. if(!branch) {
  269. // console.warn('No branch was specified detecting from working client.')
  270. // First check if working client exists.
  271. // if (existsSync(instanceroot + '/' + repo)) {
  272. pullCmd= gitops.getdiscoverbranchcmd(repo)
  273. // }
  274. // else performpull
  275. }
  276. // var pullCmd = [gitInstallDir
  277. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  278. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  279. if(branch) {
  280. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  281. var pullCmd = [ gitbash
  282. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  283. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  284. }
  285. // var pullCmd = ['pullall', [], { cwd : repo }]
  286. if (useGitPull) pullCmd = ['git', ['pull'], {
  287. inherit: true, shell: true,
  288. cwd: instanceroot + '/' + repo
  289. // , env: process.env
  290. , runas: processedArgs.runas
  291. , title: `git pull ${repo}`
  292. }]
  293. return pullCmd
  294. }
  295. // PB : TODO -- Use queueing with async tasks..
  296. var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  297. var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
  298. var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch)
  299. // var waitForBatchAdditions = function(){
  300. // return pT;
  301. // }
  302. // Execute is implied.
  303. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  304. // else
  305. return pT() // Execute it.
  306. }
  307. var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  308. // PB : TODO -- Handle no branch passed in case.
  309. // if(!branch) { throw 'No branch specified' }
  310. var repo = repodef.repo;
  311. elevatedBatch = elevatedBatch || [];
  312. regularBatch = regularBatch || [];
  313. try{
  314. var exists = existsSync(instanceroot + '/' + repo)
  315. }
  316. catch(e){
  317. exists = false
  318. console.log(e)
  319. }
  320. function initTask(etask){
  321. etask.info = { repo }
  322. etask.errHandler = errHandler
  323. etask.statuslog = statuslog
  324. etask.processedArgs = processedArgs
  325. etask.selectedinstance = selectedinstance
  326. etask.runtimestamp = runtimestamp
  327. etask.ENV = ENV
  328. elevatedBatch.info = { repo }
  329. elevatedBatch.errHandler = errHandler
  330. elevatedBatch.statuslog = statuslog
  331. elevatedBatch.processedArgs = processedArgs
  332. elevatedBatch.selectedinstance = selectedinstance
  333. elevatedBatch.runtimestamp = runtimestamp
  334. elevatedBatch.ENV = ENV
  335. }
  336. if (exists) {
  337. var branchprint = branch ? ' branch :' + branch : '';
  338. var task = ()=>{
  339. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  340. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  341. return true;
  342. })
  343. }
  344. initTask(task)
  345. if(repodef.requiresElevation) {
  346. if(elevatedBatch.length === 1) { initTask(elevatedBatch[0]) } // PB : TDOO -- Make sure first task also has run context. May need to be moved to win_verse
  347. elevatedBatch.push(shell_verse.getElevatedTask( task ));
  348. return elevatedBatch[elevatedBatch.length-1]
  349. }
  350. else {
  351. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  352. return regularBatch[regularBatch.length-1]
  353. }
  354. }
  355. else {
  356. console.log('cloning ' + repo)
  357. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  358. var task = ()=>{
  359. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
  360. {
  361. inherit: true, shell: true,
  362. env: process.env
  363. , cwd : instanceroot
  364. , runas: processedArgs.runas
  365. }).then(() => {
  366. var task = ()=>{
  367. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  368. {
  369. inherit: true, shell: true,
  370. env: process.env
  371. , cwd: instanceroot + '/' + repo
  372. , runas: processedArgs.runas
  373. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  374. })
  375. }
  376. initTask(task)
  377. if(repodef.requiresElevation) {
  378. elevatedBatch.push(shell_verse.getElevatedTask( task ));
  379. return elevatedBatch[elevatedBatch.length-1]
  380. }
  381. else {
  382. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  383. return regularBatch[regularBatch.length-1]
  384. }
  385. })
  386. }
  387. initTask(task)
  388. if(repodef.requiresElevation) {
  389. elevatedBatch.push(shell_verse.getElevatedTask( task ));
  390. return elevatedBatch[elevatedBatch.length-1]
  391. }
  392. else {
  393. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  394. return regularBatch[regularBatch.length-1]
  395. }
  396. }
  397. }
  398. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  399. var defaultRepoOwner = 'chess';
  400. var elevatedRunasRepos = null
  401. var gitRepos = null
  402. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  403. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  404. var dbForLabel = function (label) {
  405. var dbsForLabel = {
  406. devmysql: 'mysql'
  407. , development: 'mssql'
  408. , production: 'mssql'
  409. }
  410. return dbsForLabel[label] || 'mysql'
  411. }
  412. // SAM : TODO Use nodeshellexec where to detect git installation dir
  413. var gitbash = shell_verse.getbash()
  414. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  415. // Relevant git repos
  416. var exludeMergeRepos = [];
  417. var useGitPull = processedArgs.useGitPull || false;
  418. var configPromise = null
  419. var op = {
  420. 'h': () => { console.log(elxr.help()); return '-h' }
  421. , 'clean' : () => {
  422. // delete all node_module folders and links.
  423. var tasklist = [];
  424. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  425. return Promise.all(tasklist)
  426. }
  427. // , 'undefined': () => { return acquireChoices( {} ); }
  428. , 'reset': () => {
  429. // Reset NPM packages semver so major versions can be updated.
  430. const fs = require('fs')
  431. const wipeDependencies = (__package) => {
  432. const file = fs.readFileSync(__package + '/package.json')
  433. const content = JSON.parse(file)
  434. for (var devDep in content.devDependencies) {
  435. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  436. content.devDependencies[devDep] = '*';
  437. }
  438. }
  439. for (var dep in content.dependencies) {
  440. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  441. content.dependencies[dep] = '*';
  442. }
  443. }
  444. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  445. }
  446. var repos = ['client'];
  447. // repos = gitRepos;
  448. repos.forEach(wipeDependencies)
  449. // if (require.main === module) {
  450. // } else {
  451. // module.exports = wipeDependencies
  452. // }
  453. }
  454. , 'upgrade': () => {
  455. console.log('upgrade.......')
  456. var tasks = [
  457. () => {
  458. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  459. inherit: true, shell: true
  460. , env: process.env
  461. }).catch((e) => { console.error(e) })
  462. p.position = 1;
  463. console.log('One')
  464. return p;
  465. }
  466. , () => {
  467. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  468. inherit: true, shell: true
  469. , env: process.env
  470. }).catch((e) => { console.error(e) })
  471. p.position = 2;
  472. console.log('Two')
  473. return p;
  474. }
  475. , () => {
  476. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  477. inherit: true, shell: true
  478. , env: process.env
  479. }).catch((e) => { console.error(e) })
  480. p.position = 3;
  481. console.log('Three')
  482. return p;
  483. }
  484. , () => {
  485. var p = nodeShellExec('n', ['latest'], {
  486. inherit: true, shell: true
  487. , env: process.env
  488. }).catch((e) => { console.error(e) })
  489. p.position = 4;
  490. console.log('Four')
  491. return p;
  492. }
  493. ]
  494. any(tasks)
  495. console.log('.......done')
  496. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  497. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  498. console.info('Uninstalling existing ember globally');
  499. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  500. stdio: ['pipe', process.stdout, process.stderr],
  501. inherit: true,
  502. shell: true,
  503. cwd: path.dirname(__dirname),
  504. env: env
  505. })
  506. step1.on('close', () => {
  507. console.info('Installing ember globally');
  508. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  509. stdio: ['pipe', process.stdout, process.stderr],
  510. inherit: true,
  511. shell: true,
  512. cwd: path.dirname(__dirname),
  513. env: env
  514. })
  515. step2.on('close', () => {
  516. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  517. stdio: ['pipe', process.stdout, process.stderr],
  518. inherit: true,
  519. shell: true,
  520. cwd: path.dirname(__dirname),
  521. env: env
  522. })
  523. })
  524. })
  525. }
  526. , 'push': () => {
  527. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  528. // init remote bare from local
  529. // pushandinitremotebare
  530. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  531. // connect to repo server -- net use 172.16.0.27
  532. // cd 172.16.0.27/repos/
  533. // mkdir repo.git
  534. // cd repo.git
  535. // git init --bare
  536. // cd localrepo
  537. // git remote rename origin githubclone
  538. // git remote add origin //172.16.0.27/repos/repo.git
  539. // git push origin master
  540. var repo = processedArgs._[1];
  541. var sequentialTaskShellCommands = [];
  542. if (!existsSync(`Z:/${repo}.git`)) {
  543. sequentialTaskShellCommands = [
  544. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  545. // inherit : true, shell: true
  546. // , env: process.env
  547. // }]
  548. ['pwd', { cwd: 'Z:', inherit: true }]
  549. , ['mkdir', [`${repo}.git`], {
  550. cwd: `Z:`
  551. , inherit: true, shell: true
  552. , env: process.env
  553. }]
  554. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  555. , ['git', ['init', '--bare'], {
  556. cwd: `Z:/${repo}.git`
  557. , inherit: true, shell: true
  558. , env: process.env
  559. }]
  560. // PB : TODO -- Do this conditionally only...
  561. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  562. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  563. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  564. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  565. // PB : TODO -- If threre is a gitbubclone origin
  566. // Set the master to pull from the local repo.
  567. ]
  568. if (!existsSync(`Z:`)) {
  569. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  570. inherit: true, shell: true
  571. , env: process.env
  572. }])
  573. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  574. // throw 'done'
  575. }
  576. }
  577. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  578. // console.dir(sequentialTaskShellCommands);
  579. var tasks = [];
  580. sequentialTaskShellCommands.forEach(shellcmd => {
  581. // console.log(shellcmd)
  582. tasks.push(() => {
  583. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  584. return p;
  585. })
  586. })
  587. any(tasks);
  588. }
  589. , 'is-git-repo': (dir) => {
  590. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  591. }
  592. // git remote equivalents...
  593. // git branch --set-upstream-to=elixir-unc/master master
  594. // git push --set-upstream elixir-unc branch..
  595. , 'remote': (args) => {
  596. // Subcommands!
  597. // PB : TODO -- we can now pass in hypehnated args...
  598. if(!processedArgs.v) return false; // Only -v is supported presently..
  599. var serial_perform = (repo) => {
  600. var options = { cwd: instanceroot + '/' + repo }
  601. return [
  602. ['git', ['remote', '-v'], options]
  603. ]
  604. }
  605. var x = (args) => {
  606. var tasq = () => {
  607. // console.log(args)
  608. return nodeShellExec.apply(null, args).catch(e => {
  609. // We continue on failure.
  610. console.error(tasq.toString())
  611. })
  612. }
  613. tasq.toString = function(){
  614. return JSON.stringify(args)
  615. }
  616. return tasq;
  617. }
  618. var perform = (dir) => {
  619. return any(serial_perform(dir.name).map(x))
  620. }
  621. dirs(perform)
  622. }
  623. , 'remote set-url': (args) => {
  624. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  625. var __args = {
  626. remotename : args.remotename || processedArgs._[2]
  627. , url : args.url || processedArgs._[3]
  628. }
  629. // pushable doesn't mean the remote doesn't support being pushed to.
  630. // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
  631. // PB : TODO -- change this to enablepushing.
  632. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  633. var pushable = processedArgs.pushable || false;
  634. remotename = __args.remotename
  635. url = __args.url
  636. var serial_perform_git_seturl = (repo) => {
  637. var options = { cwd: instanceroot + '/' + repo }
  638. // console.log(repo)
  639. if (pushable) {
  640. return [
  641. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  642. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  643. ]
  644. }
  645. else {
  646. return [
  647. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  648. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  649. ]
  650. }
  651. }
  652. var x = (args) => {
  653. var tasq = () => {
  654. // console.log(args)
  655. return nodeShellExec.apply(null, args).catch(e => {
  656. // We continue on failure.
  657. console.error(tasq.toString())
  658. })
  659. }
  660. tasq.toString = function(){
  661. return JSON.stringify(args)
  662. }
  663. return tasq;
  664. }
  665. var perform_git_seturl = (dir) => {
  666. op['is-git-repo'](dir).then((logEntry) => {
  667. return any(serial_perform_git_seturl(dir.name).map(x))
  668. }).catch((e) => {
  669. // console.log('Failed : ' + dir.name)
  670. })
  671. }
  672. dirs(perform_git_seturl)
  673. }
  674. // , 'reset' : ()=>{
  675. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  676. // // Reset the whole installation pertaining to this elxr folder.
  677. // }
  678. , 'remote exists': (args) => {
  679. var __args = {
  680. remotename : args.remotename|| processedArgs._[2]
  681. , url : args.url || processedArgs._[3]
  682. , branch : args.branch || processedArgs._[4]
  683. }
  684. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  685. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  686. var commands = [
  687. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  688. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  689. ['git', ['remote', '-v'], utils.assign( {
  690. evaluateResult : function(err, result){
  691. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  692. var remotes = []
  693. var found = false;
  694. console.dir(result.messages)
  695. console.log(result + '---------------')
  696. result.messages.forEach( (line)=> {
  697. console.log(line + '$$$$$$$$$$$$$$$$$$$$')
  698. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  699. if(matches) {
  700. var remote = {};
  701. remote[matches[1]] = matches[2];
  702. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  703. found = true;
  704. result.url = remote[remotename];
  705. }
  706. }
  707. })
  708. console.dir(remotes)
  709. return [
  710. found
  711. , result
  712. ]
  713. }
  714. } , options) ]
  715. , function(prevserialtaskresult) {
  716. console.log('================================')
  717. var url = __args || prevserialtaskresult.url;
  718. console.dir(prevserialtaskresult)
  719. return getshelltask(['git', ['ls-remote', url], utils.assign( {
  720. evaluateResult : function(err, result){
  721. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  722. // `fatal: repository '${__args.url}/' not found`
  723. var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  724. return [
  725. !hasfailed, result
  726. ]
  727. }
  728. } , options) ])()
  729. }
  730. ]
  731. var mapped = commands.map(callshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  732. return any(mapped).then( allresolved =>{
  733. console.dir(allresolved)
  734. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  735. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  736. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  737. : console.log('was not added as a remote but url is currently accessible.')
  738. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  739. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  740. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  741. : [0, 1] // => was not added and remote and url is accessible.
  742. })
  743. }
  744. , 'remote refresh': (args) => {
  745. var __args = {
  746. remotename : args.remotename|| processedArgs._[2]
  747. , url : args.url || processedArgs._[3]
  748. , branch : args.branch || processedArgs._[4]
  749. }
  750. // use the repo manifest to create missing remotes.
  751. function perform_remote_refresh(dir){
  752. var repo = dir.name
  753. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  754. try {
  755. var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null, selectedinstance).remotes || [];
  756. }
  757. catch(e){
  758. var remotes = []
  759. }
  760. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  761. // console.dir(remotes)
  762. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  763. console.log('Processing : ' + dir.name)
  764. var branch = __branch
  765. __args.repo = repo
  766. __args.branch = __branch
  767. var promises = []
  768. remotes.forEach(remote =>{
  769. Object.keys(remote).forEach(remotename => {
  770. __args.remotename = remotename
  771. __args.url = remote[remotename]
  772. promises.push( op['remote exists']( __args ).then( exists => {
  773. if(!exists[0]) {
  774. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ) }
  775. else return op['remote add']( { remotename,
  776. // PB : TODO -- use the most accessible remote instead of the first available.
  777. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  778. } )
  779. }
  780. })
  781. )
  782. })
  783. })
  784. return Promise.all(promises)
  785. })
  786. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  787. }
  788. return dirs(perform_remote_refresh)
  789. }
  790. , 'remote add': (args) => {
  791. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  792. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  793. // That explicitly has a remote name prefix.
  794. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  795. // git branch branch_name -u your_new_remote/branch_name -- older versions
  796. // git branch -vv -- Detect which branch are we tracking.
  797. // default upstream should be users own fork.
  798. // Also need alias branches to
  799. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  800. // probably git merge from all remotes... and relevant branches...
  801. // alias pushall='for i in `git remote`; do git push $i; done;'
  802. // alias pullall='for i in `git remote`; do git pull $i; done;'
  803. // args === processedArgs ? args = {} : null;
  804. var __args = {
  805. remotename : args.remotename|| processedArgs._[2]
  806. , url : args.url || processedArgs._[3]
  807. , branch : args.branch || processedArgs._[4]
  808. }
  809. var remotename = __args.remotename
  810. var url = __args.url
  811. var branch = __args.branch
  812. var pushable = processedArgs.pushable || false;
  813. var serial_perform_git_add = (repo) => {
  814. var options = { cwd: instanceroot + '/' + repo }
  815. // console.log(repo)
  816. if (pushable) {
  817. return [
  818. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  819. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  820. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  821. ]
  822. }
  823. else {
  824. return [
  825. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  826. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  827. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  828. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  829. ]
  830. }
  831. }
  832. var x = (args) => {
  833. return () => {
  834. // console.log(args)
  835. return nodeShellExec.apply(null, args)
  836. }
  837. // return Promise.resolve(true)
  838. }
  839. var perform_git_add = (dir) => {
  840. op['is-git-repo'](dir).then((logEntry) => {
  841. // console.log(code)
  842. if (logEntry.success) {
  843. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  844. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  845. })
  846. .catch((e) => {
  847. any(serial_perform_git_add(dir.name).map(x))
  848. })
  849. }
  850. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  851. }).catch((e) => {
  852. console.log('Failed : ' + dir.name)
  853. })
  854. }
  855. const { readdir } = require("fs").promises
  856. dirs(perform_git_add)
  857. }
  858. , 'remote remove': (args) => {
  859. var __args = {
  860. remotename : args.remotename|| processedArgs._[2]
  861. }
  862. var remotename = __args.remotename
  863. var serial_perform_git_remove = (repo) => {
  864. var options = { cwd: instanceroot + '/' + repo }
  865. // console.log(repo)
  866. return [
  867. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  868. ]
  869. }
  870. var x = (args) => {
  871. return () => {
  872. // console.log(args)
  873. return nodeShellExec.apply(null, args)
  874. }
  875. // return Promise.resolve(true)
  876. }
  877. var perform_git_remove = (dir) => {
  878. op['is-git-repo'](dir).then((logEntry) => {
  879. // console.log(code)
  880. if (logEntry.success) {
  881. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  882. any(serial_perform_git_remove(dir.name).map(x))
  883. })
  884. .catch((e) => {
  885. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  886. })
  887. }
  888. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  889. }).catch((e) => {
  890. // console.log('Failed : ' + dir.name)
  891. })
  892. }
  893. const { readdir } = require("fs").promises
  894. dirs(perform_git_remove)
  895. }
  896. , 'init-gitea': (user) => {
  897. user = user || processedArgs._[1]
  898. if (!user) throw 'User name required'
  899. var serial_perform_init_gitea = (repo) => {
  900. var options = { cwd: instanceroot + '/' + repo }
  901. // console.log(repo)
  902. return [
  903. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  904. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  905. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  906. ]
  907. }
  908. var x = (args) => {
  909. return () => {
  910. // console.log(args)
  911. return nodeShellExec.apply(null, args)
  912. }
  913. // return Promise.resolve(true)
  914. }
  915. var perform_init_gitea = (dir) => {
  916. op['is-git-repo'](dir).then((logEntry) => {
  917. // console.log(code)
  918. if (logEntry.success) {
  919. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  920. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  921. })
  922. .catch((e) => {
  923. any(serial_perform_init_gitea(dir.name).map(x))
  924. })
  925. }
  926. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  927. }).catch((e) => {
  928. // console.log('Failed : ' + dir.name)
  929. })
  930. }
  931. const { readdir } = require("fs").promises
  932. dirs(perform_init_gitea)
  933. }
  934. , 'syncmaster': (label) => {
  935. // Usage :
  936. // elxr pull -- Defaults to run config
  937. var env = Object.assign({}, process.env); // Shallow clone it.
  938. // console.dir(env)
  939. console.log('Running exlr pull : ' + path.dirname(__dirname))
  940. if (!processedArgs.runas) gitRepos.map((def) => performPull(def, def.branch || 'master'))
  941. var etask = ()=>{
  942. return any(elevatedRunasRepos.map((def) => performPull(def, def.branch || 'master'))).then(() => {
  943. fs.writeFileSync('run.done', 'success')
  944. }).catch(() => {
  945. fs.writeFileSync('run.done', 'error')
  946. })
  947. }
  948. etask.statuslog = statuslog
  949. etask.selectedinstance = selectedinstance
  950. etask.processedArgs = processedArgs
  951. etask.runtimestamp = runtimestamp
  952. etask.ENV = ENV
  953. return shell_verse.runElevated(etask)
  954. }
  955. , 'repo-relocate' : function(args){
  956. // relocate a subfolder in source repo to same subfolder in target repo with history.
  957. var args = args || {
  958. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  959. , folder : processedArgs._[3] || 'server'
  960. , sourcerepo : processedArgs._[2] || 'client'
  961. , targetrepo : processedArgs._[1] || 'elixir-server'
  962. }
  963. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  964. // , stdio: ['pipe', process.stdout, process.stderr]
  965. , inherit: true,
  966. shell: true,
  967. env: process.env
  968. , runas: processedArgs.runas
  969. }
  970. return op['repo-split'](args).then(()=>{
  971. return op['repo-merge'](args).then(()=>{
  972. // cleanup folder from source.
  973. var cmdseq = [
  974. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  975. // commits have to intentional...
  976. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  977. ]
  978. return any(cmdseq.map(getshelltask))
  979. })
  980. }).catch(e=>{console.error(e)})
  981. }
  982. , 'repo-split' : function(args) {
  983. // https://gist.github.com/smdabdoub/17065c348289158277b5
  984. /**
  985. * Eg : folder, remotebase, sourcerepo, targetrepo
  986. * args.folder = 'server'
  987. * args.remotebase = 'https://git.bbh/chess/'
  988. * args.sourcerepo = 'client'
  989. * args.targetrepo = 'elixir-server'
  990. */
  991. var args = args || {
  992. folder : 'server'
  993. , remotebase : 'http://git.bbh/chess/'
  994. , sourcerepo : 'client'
  995. , targetrepo : 'elixir-server'
  996. }
  997. var options = { cwd: `${instanceroot}/relocate`
  998. // , stdio: ['pipe', process.stdout, process.stderr]
  999. , inherit: true,
  1000. shell: true,
  1001. env: process.env
  1002. , runas: processedArgs.runas
  1003. }
  1004. var cmdseq = [
  1005. // create a temporary working dir in current folder where we started execution.
  1006. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  1007. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  1008. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  1009. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  1010. ]
  1011. return any(cmdseq.map(getshelltask)).then(() => {
  1012. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1013. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  1014. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1015. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  1016. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  1017. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  1018. // subtree split and filter-branch are options. We currently use repo-filter.
  1019. return op['filter-repo'](args)
  1020. }).catch(e=>{console.error(e); throw 'failed'})
  1021. }
  1022. , 'repo-merge' : function(args) {
  1023. // Merge source repo into target repo
  1024. var args = args || {
  1025. folder : 'server'
  1026. , remotebase : 'http://git.bbh/chess/'
  1027. , sourcerepo : 'client'
  1028. , targetrepo : 'elixir-server'
  1029. }
  1030. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1031. // , stdio: ['pipe', process.stdout, process.stderr]
  1032. , inherit: true,
  1033. shell: true,
  1034. env: process.env
  1035. , runas: processedArgs.runas
  1036. }
  1037. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  1038. // , stdio: ['pipe', process.stdout, process.stderr]
  1039. , inherit: true,
  1040. shell: true,
  1041. env: process.env
  1042. , runas: processedArgs.runas
  1043. }
  1044. var cmdseq = [
  1045. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  1046. , targetrepooptions ]
  1047. // , ['git', ['push', targetrepooptions ] // manual push for now..
  1048. ]
  1049. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  1050. }
  1051. , 'filter-repo' : function(args){
  1052. // Merge source repo into target repo
  1053. var args = args || {
  1054. folder : 'server'
  1055. , remotebase : 'http://git.bbh/chess/'
  1056. , targetrepo : 'elixir-server'
  1057. }
  1058. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1059. , inherit: true, shell: true
  1060. , env: process.env
  1061. , runas: processedArgs.runas
  1062. }
  1063. var cmdseq = [
  1064. // git checkout -b feature/merge-old-project
  1065. // git remote add src-project ../src-project
  1066. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  1067. ]
  1068. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  1069. }
  1070. , 'filter-branch' : function(preservefolder, repo){
  1071. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  1072. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  1073. // Preserve a specific folder.
  1074. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  1075. /*
  1076. git clone repo reposplit
  1077. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  1078. git remote rm origin
  1079. */
  1080. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  1081. }
  1082. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  1083. // // Merge repo2 into a subfolder in repo1
  1084. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  1085. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  1086. // /*
  1087. // cd repo1
  1088. // git remote add -f tempmergesource ../{{mergesource}}/.git
  1089. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  1090. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  1091. // git commit
  1092. // // Repair History
  1093. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  1094. // #!/usr/bin/env bash
  1095. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  1096. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  1097. // subdir=server
  1098. // git filter-branch --tree-filter '
  1099. // first='"$first"'
  1100. // last='"$last"'
  1101. // subdir='"$subdir"'
  1102. // log_file=/tmp/filter.log
  1103. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  1104. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  1105. // echo "=== $GIT_COMMIT: making changes"
  1106. // files=$(git ls-tree --name-only $GIT_COMMIT)
  1107. // mkdir -p $subdir
  1108. // for i in $files; do
  1109. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  1110. // done
  1111. // else
  1112. // echo "=== $GIT_COMMIT: ignoring"
  1113. // fi \
  1114. // >> $log_file
  1115. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  1116. // status=0 # tell tree-filter never to fail
  1117. // '
  1118. // git remote rm tempmergesource
  1119. // */
  1120. // // better alternative for history
  1121. // /**
  1122. // *
  1123. // git clone git@server.com:old-project.git
  1124. // git clone git@server.com:new-project.git
  1125. // cd old-project
  1126. // mkdir old-project
  1127. // git mv !(old-project) old-project
  1128. // ls -la and gt mv hidden files ....
  1129. // git commit -a -S -m “Moving old project into its own subdirectory”
  1130. // cd ../new-project
  1131. // git remote add old-project ../old-project
  1132. // git fetch old-project
  1133. // git checkout -b feature/merge-old-project
  1134. // git merge -S --allow-unrelated-histories old-project/master
  1135. // git push origin feature/merge-old-project
  1136. // git remote rm old-project
  1137. // */
  1138. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  1139. // }
  1140. , 'pull' : (label) => {
  1141. // Usage :
  1142. // elxr pull -- Defaults to run config
  1143. return elxr.getpulltask(selectedinstance)
  1144. }
  1145. , 'isInstalled': () => {
  1146. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  1147. console.log(processedArgs._[1] + ' exists.')
  1148. return true;
  1149. });
  1150. }
  1151. , 'c' : ()=>{
  1152. }
  1153. , 'i' : () => {
  1154. var tasks = []
  1155. // tasks.push(op['pull']);
  1156. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1157. tasks.push(op['use']) // Will pull repos...
  1158. op['npmi'].statuslog = statuslog
  1159. tasks.push(shell_verse.getNonElevatedTask(op['npmi'])) // We do not run npm i with elevated privilege for security reasons.
  1160. // var tasksdefs = [
  1161. // ['elxr', ['pull']]
  1162. // , ['elxr', ['use', 'elixir']]
  1163. // , ['elxr', ['npmi']]
  1164. // ]
  1165. // tasksdefs.forEach(tasksdef=>{
  1166. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1167. // })
  1168. return any(tasks);
  1169. }
  1170. , 'npmi': () => {
  1171. var tasks = [];
  1172. // Build fails without babel...
  1173. tasks.push(getShellTask(
  1174. 'npm',[ 'i', '-g', 'babel-cli' ]
  1175. ) )
  1176. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1177. // npmbuildrepos = []
  1178. npmbuildrepos.forEach(repo => {
  1179. tasks.push(() => {
  1180. return nodeShellExec('npm', ['i --force'], {
  1181. inherit: true, shell: true
  1182. , cwd: instanceroot + '/' + repo
  1183. , env: process.env
  1184. , title: `npm i for ${repo}`
  1185. }).catch((e) => {
  1186. console.error('Ignoring Benign Error'); console.error(e);
  1187. }).then(() => {
  1188. console.log(`--npm run build for ${repo}--------------------`)
  1189. return nodeShellExec('npm', ['run build'], {
  1190. inherit: true, shell: true
  1191. , cwd: instanceroot + '/' + repo
  1192. , env: process.env
  1193. , title: `npm run build for ${repo}`
  1194. }).then(Tasq.then).catch(Tasq.catch)
  1195. })
  1196. })
  1197. })
  1198. return any(tasks).then(() => {
  1199. gitRepos.push({ repo : 'chess-server-lib/server'});
  1200. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1201. // console.dir(gitRepos)
  1202. // throw ""
  1203. // gitRepos = [
  1204. // // 'bbhverse', 'serververse', 'elixir-server',
  1205. // // 'clientverse',
  1206. // 'client'
  1207. // ];
  1208. var rmtasks = []
  1209. var repotasks = []
  1210. var env = Object.assign({}, process.env)
  1211. delete env.NODE_ENV
  1212. gitRepos.forEach(repodef => {
  1213. rmtasks.push(
  1214. // () => {
  1215. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1216. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1217. callshelltask(['rm', ['package-lock.json'], {
  1218. inherit: true, shell: true
  1219. , cwd: instanceroot + '/' + repodef.repo
  1220. , env: process.env
  1221. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1222. }])
  1223. .then(()=>{
  1224. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1225. }).catch((e) => { console.error(e) })
  1226. // }
  1227. )
  1228. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1229. repotasks.push(
  1230. () => {
  1231. console.log(`--npm i for ${repodef.repo}--------------------`)
  1232. var p = nodeShellExec('npm', ['i', '--force'], {
  1233. inherit: true, shell: true
  1234. , cwd: instanceroot + '/' + repodef.repo
  1235. , env
  1236. , title: `npm i for ${repodef.repo}`
  1237. }).then(Tasq.then).catch(Tasq.catch)
  1238. return p;
  1239. })
  1240. }
  1241. })
  1242. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  1243. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1244. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1245. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1246. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1247. // Second time try also doesnt work.
  1248. // repotasks.push(
  1249. // () => {
  1250. // var env = Object.assign({}, process.env)
  1251. // delete env.NODE_ENV
  1252. // console.log(`--------------------second time npm i for client--------------------`)
  1253. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1254. // // return nodeShellExec('npm', ['i --force'], {
  1255. // inherit: true, shell: true
  1256. // , cwd: instanceroot + '/' + 'client'
  1257. // , env
  1258. // , title: `npm i for client`
  1259. // }).then(Tasq.then).catch(Tasq.catch)
  1260. // })
  1261. var bowerRepos = [{ repo : 'client'}]
  1262. var bowertasks = []
  1263. bowerRepos.forEach(repodef => {
  1264. bowertasks.push(() => {
  1265. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1266. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1267. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1268. inherit: true, shell: true
  1269. , cwd: instanceroot + '/' + repodef.repo
  1270. , env: process.env
  1271. , title: `bower i for ${repodef.repo}`
  1272. }).then(Tasq.then).catch(Tasq.catch)
  1273. return p;
  1274. })
  1275. })
  1276. // console.log('rmtasks.length : ' + rmtasks.length)
  1277. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  1278. }).catch(e => {
  1279. console.error(e)
  1280. }).finally(statuslog.finally)
  1281. }
  1282. , 'start': (args) => {
  1283. var label = clioverrides.cmd
  1284. var env = Object.assign({}, process.env); // Shallow clone it.
  1285. env.NODE_ENV = clioverrides.node_env || 'development';
  1286. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  1287. function startFn( o ){
  1288. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  1289. console.log(`Starting ${o.name}.`);
  1290. var childPromise = nodeShellExec('cmd', ['/k', getCmdString(cmd) ], {
  1291. // inherit : true,
  1292. shell: true,
  1293. detached: true,
  1294. stdio: 'ignore',
  1295. cwd: instanceroot + o.path
  1296. , env: env
  1297. })
  1298. var child = childPromise.process;
  1299. var cpid = child.pid
  1300. if (typeof child.pid !== 'undefined') {
  1301. childPromise.then(()=>{
  1302. console.log(` *** started Elixir Loopback Server PID(${cpid}) : NODE_ENV=${clioverrides.node_env} ${cmd}`);
  1303. fs.writeFileSync('.elixir-server.elixir.server.pid', '' + cpid)
  1304. })
  1305. .catch(e => console.errror(e) )
  1306. }
  1307. }
  1308. if(clioverrides.node_env === 'development') {
  1309. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1310. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server' } )
  1311. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server' } )
  1312. // cmd = 'node'()
  1313. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1314. // inherit : true,
  1315. // shell: true, detached: true,
  1316. // cwd : 'qms/server',
  1317. // env: env,
  1318. // shell : true
  1319. // })
  1320. // nodeShellExec('ember', ['s'], {
  1321. // // inherit : true,
  1322. // shell: true, detached: true,
  1323. // cwd : 'client/',
  1324. // env: env
  1325. // })
  1326. console.log('Starting Elixir Client Host.');
  1327. var cmd = ['ember', ['s']]
  1328. var childPromise = nodeShellExec(...cmd, {
  1329. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1330. // PB : TODO -- ember debugging.
  1331. // inherit : true,
  1332. shell: true,
  1333. detached: true,
  1334. stdio: 'ignore',
  1335. cwd: instanceroot + '/' + 'client'
  1336. , env: env
  1337. })
  1338. // .catch(e=>console.error(e))
  1339. child = childPromise.process;
  1340. if (typeof child.pid !== 'undefined') {
  1341. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1342. fs.writeFileSync('.client.server.pid', child.pid, {
  1343. encoding: 'utf8'
  1344. })
  1345. }
  1346. }
  1347. }
  1348. , 'stop': (label) => {
  1349. const kill = require('tree-kill');
  1350. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1351. encoding: 'utf8'
  1352. })
  1353. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1354. console.log(serverPid)
  1355. kill(serverPid)
  1356. serverPid = fs.readFileSync('.express.server.pid', {
  1357. encoding: 'utf8'
  1358. })
  1359. fs.unlinkSync('.express.server.pid')
  1360. console.log(serverPid)
  1361. kill(serverPid)
  1362. }
  1363. , 'model' : () => {
  1364. var etask = ()=>{
  1365. var tasks = [
  1366. () => {
  1367. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1368. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1369. inherit: true, shell: true
  1370. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1371. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1372. , env: process.env
  1373. }).catch((e) => { console.error(e) })
  1374. return p;
  1375. }
  1376. ];
  1377. return any(tasks).then(() => {
  1378. fs.writeFileSync('run.done', 'success')
  1379. }).catch(() => {
  1380. fs.writeFileSync('run.done', 'error')
  1381. })
  1382. }
  1383. etask.statuslog = statuslog
  1384. etask.selectedinstance = selectedinstance
  1385. etask.processedArgs = processedArgs
  1386. etask.runtimestamp = runtimestamp
  1387. etask.ENV = ENV
  1388. return shell_verse.runElevated(etask)
  1389. }
  1390. , 'use' : () => {
  1391. // use a certain named instance.
  1392. // Eg :
  1393. // 1) elxr use elixir
  1394. // 2) elxr use cihsr
  1395. // If environment is not specified defaults to development.
  1396. // 1) NODE=test elxr use elixir
  1397. /*// Steps
  1398. 1) Delete Config and Data symlinks
  1399. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1400. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1401. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1402. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1403. */
  1404. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1405. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1406. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1407. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1408. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1409. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1410. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1411. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1412. if (existsSync('config') && existsSync('data')){
  1413. return
  1414. }
  1415. }
  1416. var tasks = [
  1417. () => {
  1418. var promise = new Promise((resolve, reject)=>{
  1419. existslink('config', function(err, data){
  1420. if(data) {
  1421. var p = shell_verse.removeJuncionOrLink('config')
  1422. .then(()=>{resolve(true)})
  1423. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1424. }
  1425. else resolve(false)
  1426. })
  1427. })
  1428. return promise;
  1429. },
  1430. () => {
  1431. var promise = new Promise((resolve, reject)=>{
  1432. existslink('data', function(err, data){
  1433. if(data) {
  1434. var p = shell_verse.removeJuncionOrLink('data')
  1435. .then(()=>{resolve(true)})
  1436. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1437. }
  1438. else resolve(false)
  1439. })
  1440. })
  1441. return promise;
  1442. },
  1443. ];
  1444. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1445. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1446. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  1447. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1448. // console.log(process.env.cwd)
  1449. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1450. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1451. var checkoutMap = { 'development': 'master' }
  1452. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1453. var performPullOrCloneForBranch = (def)=>{
  1454. var promise = Promise.resolve(true)
  1455. if (!branch) {
  1456. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1457. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1458. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1459. }
  1460. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1461. }
  1462. var performCloneAndCheckout = null;
  1463. // cant use git checkout -b it fails when branch already exists.
  1464. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1465. return performPullOrCloneForBranch(def).then(()=>{
  1466. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1467. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1468. // inherit : true, shell: true,
  1469. cwd: instanceroot + '/' + def.repo
  1470. // , stdio : ignore // Use when we want to silence output completely.
  1471. , runas: processedArgs.runas
  1472. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1473. }).then(()=>{ console.log( `SUCCESS : git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}` ) }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1474. })
  1475. }
  1476. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1477. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1478. var elevatedqueue = [];
  1479. var enqueueOnce = (queue, task, def) => {
  1480. var found = queue.find(element => {
  1481. var keys = Object.keys( element )
  1482. for(var k=0; k < keys.length; k++) {
  1483. if(element[keys[k]] !== def[k]) return false;
  1484. }
  1485. })
  1486. queue.push(function(){ return task(this)}.bind(def));
  1487. }
  1488. var enqueue = (queue, task, def) => {
  1489. queue.push(function(){ return task(def)}.bind(def));
  1490. }
  1491. var mergeSources = {
  1492. 'development': null,
  1493. 'test': 'master',
  1494. 'production': 'master'
  1495. }
  1496. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1497. // Checkout is reduced to pull provided the current branch is the targetbranch
  1498. if(branch === mergesource) performCheckout = (def) => {
  1499. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1500. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1501. if(branch === __branch) return performCloneAndCheckout(def)
  1502. return performPullOrCloneForBranch(def)
  1503. })
  1504. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1505. }
  1506. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1507. var performPullAll = (def) => {
  1508. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1509. return nodeShellExec('git', ['pull', '--all'], {
  1510. // inherit : true, shell: true,
  1511. cwd: instanceroot + '/' + def.repo
  1512. , runas: processedArgs.runas
  1513. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1514. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1515. }
  1516. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1517. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1518. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1519. var performMerge = (def) => {
  1520. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1521. return nodeShellExec('git', ['merge', mergesource], {
  1522. inherit: true, shell: true,
  1523. cwd: instanceroot + '/' + def.repo
  1524. , runas: processedArgs.runas
  1525. }).catch((e) => { console.error(e) })
  1526. }
  1527. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1528. // var performRepoOperation = function(def) {
  1529. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1530. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1531. // }
  1532. return any(tasks).then(() => {
  1533. var task = ()=>{
  1534. //target is the env is we specify in elxr use command. Default is dev
  1535. //Switch to target branch
  1536. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1537. // pull or clone target branch
  1538. .then(() => {
  1539. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1540. return any(gitRepos.map((repo) => performPullAll(repo)))
  1541. })
  1542. // switch to source branch
  1543. .then( () => {
  1544. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1545. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1546. })
  1547. //Pull on merge source branch
  1548. .then( () => {
  1549. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1550. return any(gitRepos.map((repo) => performPullAll(repo)))
  1551. })
  1552. //Switch to target branch
  1553. .then( () => {
  1554. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1555. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1556. })
  1557. .then( //Merge source branch to target branch
  1558. () => {
  1559. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1560. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1561. })
  1562. }
  1563. task.statuslog = statuslog
  1564. var netask = shell_verse.getNonElevatedTask(task)
  1565. var eltask = ()=> {
  1566. var opts = {
  1567. inherit: true, shell: true
  1568. , cwd : instanceroot
  1569. , env: process.env
  1570. }
  1571. var tasks = [
  1572. () => {
  1573. // Use junctions to avoid npm package issues
  1574. var target = runconfig.use + '-' + 'config' + '-' + process.env.NODE_ENV
  1575. var p = shell_verse.createJuntionOrLink('config', target, opts)
  1576. return p;
  1577. }
  1578. ];
  1579. // if (processedArgs._[1]) {
  1580. tasks = tasks.concat( [
  1581. () => {
  1582. var dataToLink = runconfig.use + '-data' + '-' + process.env.NODE_ENV
  1583. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  1584. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  1585. return p;
  1586. }
  1587. ]
  1588. )
  1589. // }
  1590. return any(tasks).then(()=>{
  1591. // checkout target branch
  1592. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1593. // pull or clone target branch
  1594. .then(() => {
  1595. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1596. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1597. })
  1598. // switch to source branch
  1599. .then( () => {
  1600. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1601. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1602. })
  1603. //Pull on merge source branch
  1604. .then( () => {
  1605. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1606. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1607. })
  1608. //Switch to target branch
  1609. .then( () => {
  1610. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1611. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1612. })
  1613. .then( //Merge source branch to target branch
  1614. () => {
  1615. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1616. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1617. })
  1618. .then(() => {
  1619. fs.writeFileSync('run.done', 'success')
  1620. }).catch(() => {
  1621. fs.writeFileSync('run.done', 'error')
  1622. })
  1623. })
  1624. }
  1625. eltask.statuslog = statuslog
  1626. eltask.selectedinstance = selectedinstance
  1627. eltask.processedArgs = processedArgs
  1628. var etask = shell_verse.getElevatedTask(eltask)
  1629. return etask().then( ()=>{ return netask() })
  1630. }).catch((e) => {
  1631. fs.writeFileSync('run.done', 'error : ' + e)
  1632. })
  1633. // Antibiotic stewardship program.
  1634. // 1st use is fine.
  1635. // Max vials dispense
  1636. // 2nd use Pharmacy needs justification Form.
  1637. // Approval after a certain period of time.
  1638. }
  1639. , 'g' : () => {
  1640. if (processedArgs.h) {
  1641. console.log('elxr g model [modelname] => generate a model named [modelname]');
  1642. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  1643. console.log('elxr g => regenerate all known models');
  1644. return
  1645. }
  1646. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1647. // console.log('Starting directory: ' + process.cwd());
  1648. // try {
  1649. // child = child.on('close', () => { process.chdir(label) } );
  1650. // console.log('New directory: ' + process.cwd());
  1651. // }
  1652. // catch (err) {
  1653. // console.log('chdir: ' + err);
  1654. // }
  1655. // child.on('close', function(){
  1656. // var options = {
  1657. // shell : true
  1658. // , inherit : true
  1659. // // , cwd : '' + process.cwd
  1660. // // , env : process.env
  1661. // };
  1662. // nodeShellExec('git', ['init'], { inherit : true});
  1663. if (0) {
  1664. // PB : TODO -- Special google chrome profile for tests etc.
  1665. nodeShellExec('pwd', { inherit: true });
  1666. // /c/Program\ Files\ \(x86\)/Google/Chrome/Application/chrome.exe --user-data-dir=/c/chess/instances/elixir_01/data/Google/Chrome/User\ Data --profile-directory="chess"
  1667. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/admin/crud/create/item
  1668. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/tests/index.html?grep=loopback
  1669. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1670. "--profile-directory=Profile 1"
  1671. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1672. }
  1673. // nodeShellExec('npm', ['init', '-y'], options);
  1674. // nodeShellExec('npm', ['init', '-y'], options);
  1675. // })
  1676. var g = {
  1677. 'client': () => {
  1678. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1679. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1680. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1681. stdio: ['pipe', process.stdout, process.stderr],
  1682. inherit: true,
  1683. shell: true,
  1684. cwd: path.dirname(__dirname),
  1685. env: env
  1686. })
  1687. },
  1688. 'modelr': () => {
  1689. var tasks = [
  1690. () => {
  1691. var p = nodeShellExec('"ember"', [
  1692. 'g'
  1693. , 'modelr'
  1694. , processedArgs._[2]], {
  1695. inherit: true, shell: true, env: process.env
  1696. }).then(() => {
  1697. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1698. return true;
  1699. }).catch((e) => { console.error(e) })
  1700. return p;
  1701. },
  1702. () => {
  1703. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1704. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1705. chromeprefs = JSON.parse(chromeprefs)
  1706. var previous = chromeprefs.download.default_directory;
  1707. var parentDir = path.dirname(__dirname);
  1708. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1709. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1710. // PB : TODO -- detect where chrome is installed.
  1711. // PB : TODO -- set the download dir to the place where files are needed.
  1712. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1713. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1714. , '--profile-directory="chess"'
  1715. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1716. inherit: true, shell: true
  1717. , env: process.env
  1718. }).then(() => {
  1719. chromeprefs.download.default_directory = previous;
  1720. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1721. return true;
  1722. }).catch((e) => { console.error(e) })
  1723. return p;
  1724. }
  1725. ,
  1726. () => {
  1727. console.log('Browser process should have closed here....')
  1728. return true;
  1729. }
  1730. ]
  1731. any(tasks)
  1732. }
  1733. , 'undefined' : ()=>{
  1734. console.warn('Are you sure you want to refresh all the models.');
  1735. throw 'NOT YET IMPLMENTED'
  1736. }
  1737. , 'vmodel' : ()=>{
  1738. var verse = [ '__universe__/vmodel' ]
  1739. // console.dir(templateprocess(`__link____instance__server-lib__name__`, { link( ){
  1740. // return processed }, instance : 'elixir-', name : 'newmodel' } )
  1741. // )
  1742. }
  1743. }
  1744. g[processedArgs._[1]]();
  1745. }
  1746. , 'create' : () => { return createInstance(selectedinstance) }
  1747. , 'httpget' : () => {
  1748. // RESTAPI.get({
  1749. // hostname: 'git.bbh',
  1750. // // port: 443,
  1751. // protocol : 'http:',
  1752. // path: '/',
  1753. // method: 'GET'
  1754. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  1755. return createInstance(selectedinstance)
  1756. }
  1757. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  1758. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  1759. }
  1760. // independent elxr cli operations
  1761. var noprerequisites = {
  1762. add : true, 'set-url' : true, 'repo-relocate' : true
  1763. , remote : true, 'c' : true, 'h' : true
  1764. , httpget : true, getuser : true
  1765. , 'switch user' : true
  1766. , 'switch' : true
  1767. // , 'undefined' : true
  1768. }
  1769. var reconfirmcmds = { create : true }
  1770. var subcommandlabels = {
  1771. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1772. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  1773. }
  1774. var independentcmd = function(){
  1775. return false;
  1776. }
  1777. var cmds = {
  1778. remote : {
  1779. // return a interpreted set of arguments for this comd run context.
  1780. interpret() {
  1781. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  1782. }
  1783. }
  1784. , resetgitconfig : {
  1785. // return a interpreted set of arguments for this comd run context.
  1786. cmdFn : resetgitconfig
  1787. , interpret() { return { cmd : 'resetgitconfig' } }
  1788. , getPossiblePrompts(){ return {} }
  1789. , noprerequisites : true
  1790. , independentcmd : true
  1791. }
  1792. , reinit : {
  1793. // return a interpreted set of arguments for this comd run context.
  1794. cmdFn : reinit
  1795. , interpret() { return { cmd : 'reinit' } }
  1796. , getPossiblePrompts(){ return {} }
  1797. , noprerequisites : true
  1798. , independentcmd : true
  1799. , requiresElevation : true
  1800. , requires : [ generateDependencies ]
  1801. }
  1802. , init : {
  1803. // return a interpreted set of arguments for this comd run context.
  1804. cmdFn : init
  1805. , interpret() { return { cmd : 'init' } }
  1806. , getPossiblePrompts(){ return {} }
  1807. , noprerequisites : true
  1808. , independentcmd : true
  1809. , requiresElevation : true
  1810. , requires : [ generateDependencies ]
  1811. }
  1812. , switch : {
  1813. interpret() {
  1814. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  1815. , reposerver : __default.reposerver
  1816. }
  1817. }
  1818. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  1819. }
  1820. , 'switch user' : {
  1821. interpret() {
  1822. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  1823. }
  1824. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  1825. }
  1826. // Flat linear structure. Every subcommand should have a top level 'label'
  1827. , 'users' : {
  1828. // default to the users list
  1829. subcommands : { list : {} }
  1830. , cmdFn : ()=>getCredentials() // default
  1831. , cmd : 'users'
  1832. , noprerequisites : true
  1833. }
  1834. , 'users list' : {
  1835. cmdFn : ()=>getCredentials()
  1836. , cmd : 'users list'
  1837. , noprerequisites : true
  1838. }
  1839. , 'g' : {
  1840. cmdFn : op['g'] // default
  1841. , cmd : 'g'
  1842. , noprerequisites : true
  1843. , getPossiblePrompts(){ return {} }
  1844. }
  1845. , 'link' : {
  1846. 'cmd' : 'link'
  1847. // , cmdFn : function( sourecpath, filename, dir ){
  1848. // var afterTargetPath = (dir)=>{
  1849. // console.dir(dir);
  1850. // // var tasks = [
  1851. // // () => {
  1852. // // // Use junctions to avoid npm package issues
  1853. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  1854. // // inherit: true, shell: true
  1855. // // , cwd : dir || instanceroot
  1856. // // , env: process.env
  1857. // // }).catch((e) => { console.error(e) })
  1858. // // return p;
  1859. // // }
  1860. // // ];
  1861. // }
  1862. // // console.dir(process.env)
  1863. // if(!dir) getCurrentFolder().then(afterTargetPath);
  1864. // else afterTargetPath(dir)
  1865. // }
  1866. , cmdFn : function( cmdopts ){
  1867. // sourecpathandfile should include name of file name
  1868. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  1869. // console.log(processedArgs)
  1870. if(!targetfilename) return Promise.reject('error no file provided for linking')
  1871. targetdir = cmdopts.targetdir || process.env.wd
  1872. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  1873. var tasks = [
  1874. () => {
  1875. // Use junctions to avoid npm package issues
  1876. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  1877. inherit: true, shell: true
  1878. , cwd : targetdir
  1879. , env: process.env
  1880. }).catch((e) => { console.error(e) })
  1881. return p;
  1882. }
  1883. ];
  1884. var etask = ()=>{
  1885. return any(tasks).then(() => {
  1886. fs.writeFileSync('run.done', 'success')
  1887. }).catch(() => {
  1888. fs.writeFileSync('run.done', 'error')
  1889. })
  1890. }
  1891. etask.statuslog = statuslog
  1892. etask.selectedinstance = selectedinstance
  1893. etask.processedArgs = processedArgs
  1894. etask.runtimestamp = runtimestamp
  1895. etask.ENV = ENV
  1896. return shell_verse.runElevated(etask)
  1897. }
  1898. , noprerequisites : true
  1899. , privileged : true
  1900. }
  1901. }
  1902. var elxrcmd = (function(){
  1903. var __cmdprototype = function(){}
  1904. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  1905. var __cmd = {
  1906. interpret() { return { cmd : this.cmd } }
  1907. , getPossiblePrompts(){ return {} } // Requires only one argument...
  1908. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  1909. , finalized : true
  1910. }
  1911. function __createO(o){
  1912. if(o.finalized) return o;
  1913. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  1914. // console.log(subs)
  1915. // console.log(o)
  1916. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  1917. var created = utils.assign_strict({}, __cmd, cmds[o.cmd], o)
  1918. cmds[o.cmd] = created;
  1919. op[o.cmd] = created.cmdFn;
  1920. noprerequisites[o.cmd] = created.noprerequisites
  1921. return created.cmdFn;
  1922. }
  1923. function create(o){ return __createO(o) }
  1924. __cmdprototype.create = create;
  1925. return __cmdprototype;
  1926. })()
  1927. elxrcmd.create(cmds['users'])
  1928. elxrcmd.create(cmds['g'])
  1929. elxrcmd.create(cmds['link'])
  1930. var interpretrun = function(){
  1931. var cmd = processedArgs._[0];
  1932. var clioverrides = { cmd }
  1933. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  1934. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  1935. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  1936. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  1937. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1938. // return clioverrides
  1939. cmds[cmd] = {
  1940. interpret() {
  1941. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  1942. }
  1943. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  1944. instanceName : true, instanceType : true, reposerver : true } }
  1945. }
  1946. return cmds[cmd].interpret()
  1947. })()
  1948. }
  1949. var clioverrides = interpretrun()
  1950. console.dir(clioverrides)
  1951. var util = require('util');
  1952. var cliname = 'elxr';
  1953. var ver = '1.1';
  1954. var readme = `
  1955. Command syntax examples
  1956. elxr
  1957. Displays help. Same as elxr h
  1958. elxr i
  1959. Runs interactive propmts to help choose installation options.
  1960. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1961. General command syntax.
  1962. Eg: NODE_ENV=development elxr pull elixir
  1963. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1964. The specific cmd defines what the value is interpreted as.
  1965. There are several cmds that do not require an {{instancename}} parameter.
  1966. Eg: elxr remote remove origin
  1967. Git operations or passthrough external commands on all repository folders in you working directory.
  1968. Main objectives.
  1969. elxr cli is a wrapper around other shell commands and api based operations.
  1970. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1971. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1972. `;
  1973. var help = `
  1974. ${readme}
  1975. # list of commands... please refer dveloper documentation for ${cliname}
  1976. \r\n\t${
  1977. Object.keys(op).join('\r\n\t')
  1978. }
  1979. `;
  1980. var elxr = {
  1981. help() {
  1982. return chalk.cyanBright(`
  1983. -------------------------------------------------------------------------------
  1984. *** BBH Elixir ***
  1985. -------------------------------------------------------------------------------
  1986. elxr ${ver}
  1987. A cli tool for chess
  1988. ${help}
  1989. -------------------------------------------------------------------------------
  1990. `)
  1991. }
  1992. , info() {
  1993. return chalk.cyanBright(`
  1994. -------------------------------------------------------------------------------
  1995. *** BBH Elixir ***
  1996. -------------------------------------------------------------------------------
  1997. elxr ${ver}
  1998. A cli tool for chess
  1999. -------------------------------------------------------------------------------
  2000. `)
  2001. }
  2002. , getpulltask(args){
  2003. // def can be an instance config
  2004. // Or an object with many repos and elevated repos
  2005. // Or a single repo ( Either Elevated or normal. )
  2006. // USAGE
  2007. // elxr pull elixir origin master
  2008. // elxr pull
  2009. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  2010. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  2011. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  2012. // The branch pipline should feed back to master
  2013. // master -> test -> stage -> release[nnnn] -> production
  2014. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  2015. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  2016. var __args = {
  2017. remotename : args.remotename|| processedArgs._[2]
  2018. , url : args.url || processedArgs._[3]
  2019. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  2020. }
  2021. // var commands = [
  2022. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  2023. // ,
  2024. // ]
  2025. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2026. // var pullCmd = [ gitbash
  2027. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2028. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2029. var def = args || {
  2030. repos : selectedinstance.repos,
  2031. elevated : selectedinstance.elevated
  2032. }
  2033. var elevatedpulltasks = null;
  2034. if(def.repo) {
  2035. // Single repo case.
  2036. if(def.repo.requiresElevation) {
  2037. var t1 = function() {
  2038. return performPull(def).then(() => {
  2039. return true;
  2040. }).catch((e) => {
  2041. console.error(e)
  2042. }).finally(Traq.finally)
  2043. }
  2044. t1.statuslog = statuslog
  2045. t1.selectedinstance = selectedinstance
  2046. t1.processedArgs = processedArgs
  2047. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  2048. }
  2049. else {
  2050. var t2 = function(){
  2051. return performPull(def).then(() => {
  2052. console.log('pulled ' + JSON.stringify(def.repo))
  2053. return true;
  2054. }).catch((e) => {
  2055. console.error(e)
  2056. }).finally(Traq.finally)
  2057. }
  2058. t2.statuslog = statuslog
  2059. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  2060. }
  2061. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2062. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  2063. }
  2064. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  2065. console.dir(def)
  2066. var env = Object.assign({}, process.env); // Shallow clone it.
  2067. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2068. var useGitPull = processedArgs.useGitPull || false;
  2069. if(def.elevated || def.repos) {
  2070. if(def.elevated) def.requiresElevation = true;
  2071. else delete def.requiresElevation;
  2072. }
  2073. else {
  2074. if(def.requiresElevation) def.elevated = [def]
  2075. else def.repos = [def]
  2076. }
  2077. var regularpulltasks = function(){ return Promise.resolve(true) }
  2078. if(def.elevated){
  2079. elevatedpulltasks = function() {
  2080. // shell_verse.getElevatedTask( t1 )
  2081. var eBatch = []
  2082. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch))
  2083. return shell_verse.runElevatedBatch(eBatch).then(() => {
  2084. return true;
  2085. }).catch((e) => {
  2086. console.error(e)
  2087. })
  2088. }
  2089. elevatedpulltasks.statuslog = statuslog
  2090. }
  2091. if(def.repos) {
  2092. var regularpulltasks = function(){
  2093. var pendingpulls = [];
  2094. def.repos.forEach((def) => {
  2095. pendingpulls.push(
  2096. performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  2097. .catch(e => { console.log(e); throw e })
  2098. )
  2099. })
  2100. return any(pendingpulls).finally(Traq.finally)
  2101. }
  2102. regularpulltasks.statuslog = statuslog
  2103. }
  2104. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2105. // else return getTaskWithoutElevation({ regularpulltasks})
  2106. return any([ elevatedpulltasks, regularpulltasks ])
  2107. }
  2108. }
  2109. function preworkerconfig(){
  2110. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  2111. gitRepos = selectedinstance.repos
  2112. // gitRepos = ['chess-server-lib'];
  2113. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  2114. elevatedRunasRepos = selectedinstance.elevated
  2115. // Repos that should excluded from merge for releases...
  2116. exludeMergeRepos = selectedinstance.exludeMergeRepos
  2117. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  2118. // mysql -u root -p db_name < drop_all_tables.sql
  2119. var mysql = '../xampp/mysql/bin/mysql'
  2120. var mysqldump = '../xampp/mysql/bin/mysqldump'
  2121. }
  2122. // The main elxr cli process
  2123. function elxrworker() {
  2124. var __runcmd = function (label) {
  2125. var distinquishedlabel = subcommandlabels[label] || label
  2126. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  2127. }
  2128. // --runas
  2129. if (processedArgs.runas) {
  2130. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  2131. // return __runcmd('runas')
  2132. // we no longer have a runas function. This has been moved to shellverse.requestElevation...
  2133. // Each task has knowledge of requiring elevation and will handle elevation requests as needed. Preferably the task will participate in a batch and queue itself.
  2134. //
  2135. return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  2136. }
  2137. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  2138. }
  2139. // function acquireChoices(selectedinstance) {
  2140. // var hasconfig = false;
  2141. // console.warn(chalk.cyan(`
  2142. // -------------------------------------------------------------------------------
  2143. // Could not locate your preferred configuration (you may not specified it)
  2144. // You should fork the default chess configuration to customize and make it
  2145. // your own instance with a named config as
  2146. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  2147. // And then run this tool as follows
  2148. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  2149. // OR
  2150. // Run this tool with the following command to use a quick start default.
  2151. // elxr --default
  2152. // OR
  2153. // Choose one of the options below to run interactively.
  2154. // We will run your choice at the next prompt.
  2155. // -------------------------------------------------------------------------------
  2156. // `))
  2157. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  2158. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2159. // return initinstances(selectedinstance)
  2160. // })
  2161. // // var prompt = cli.prompter;
  2162. // // return prompt.ask(`Choose an option :
  2163. // // d) Install the default chess instance.
  2164. // // => elxr i chess node_env=development --default
  2165. // // n) Create your custom new instance interactively
  2166. // // => elxr i {{instanceName}} node_env={{environment}}
  2167. // // i) Choose an instance and environment to install
  2168. // // => elxr i {{instanceName}} node_env={{environment}}
  2169. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2170. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2171. // // h) Help
  2172. // // q) Quit
  2173. // // Default <= d
  2174. // // : `).then((choice) => {
  2175. // // if (choice && choice === 'd' || !choice) {
  2176. // // processedArgs._[0] = 'i'
  2177. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2178. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2179. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2180. // // }
  2181. // // else if (choice === 'h') {
  2182. // // processedArgs._[0] = 'h'
  2183. // // fs.writeFileSync('run.done', 'noop help');
  2184. // // console.log(elxr.help()); process.exit()
  2185. // // }
  2186. // // else if (choice === 'n' || choice === 'i') {
  2187. // // var p1 = cli.prompter;
  2188. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2189. // // processedArgs._[0] = 'i'
  2190. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  2191. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2192. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2193. // // if (choice === 'n') {
  2194. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2195. // // console.warn(
  2196. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  2197. // // process.exit();
  2198. // // }
  2199. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2200. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2201. // // })
  2202. // // })
  2203. // // })
  2204. // // } else if (choice === 'c') {
  2205. // // var p1 = cli.prompter;
  2206. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2207. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  2208. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2209. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2210. // // return p1.ask(`Enter cmd :
  2211. // // p) pull
  2212. // // Default <= p
  2213. // // : `).then(function (cmd) {
  2214. // // if (!cmd || cmd === 'p') {
  2215. // // processedArgs._[0] = 'pull'
  2216. // // }
  2217. // // else processedArgs._[0] = cmd
  2218. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2219. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2220. // // })
  2221. // // })
  2222. // // })
  2223. // // })
  2224. // // } else {
  2225. // // console.log(chalk.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  2226. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  2227. // // fs.writeFileSync('run.done', 'noop quit');
  2228. // // process.exit()
  2229. // // }
  2230. // // })
  2231. // }
  2232. var mergeObjByKey = function(arrOfObjs, keyName) {
  2233. var keyedDistinct = {}
  2234. var distinctArrOfObjs = []
  2235. arrOfObjs.forEach( o => {
  2236. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  2237. })
  2238. Object.keys(keyedDistinct).forEach(key => {
  2239. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  2240. })
  2241. return distinctArrOfObjs;
  2242. }
  2243. var cacheWriteInstanceConfig = function(chessinstances){
  2244. var instanceName = chessinstances['current_run'].instanceName;
  2245. var node_env = chessinstances['current_run'].node_env;
  2246. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  2247. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  2248. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  2249. }
  2250. var configs = (function(){
  2251. return {
  2252. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2253. return __acquireConfig(selected, selected.username, clusternodename
  2254. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  2255. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2256. return e; }
  2257. )
  2258. }
  2259. , ownerInstnace(selected) { return __acquireConfig(selected, selected.username, null, null
  2260. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2261. return e }
  2262. )
  2263. }
  2264. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2265. , commonInstance(selected) { return __acquireConfig(selected, defaultRepoOwner
  2266. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2267. ) }
  2268. , genericChessInstance(selected) { return __acquireConfig(selected) }
  2269. }
  2270. })()
  2271. var eNotImplemented = function(){
  2272. console.error('Not yet implemented')
  2273. process.exit()
  2274. }
  2275. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  2276. var acquireConfig = function(slections){
  2277. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2278. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  2279. return acquireData(slections)
  2280. })
  2281. }
  2282. var instanceData = (function(){
  2283. return {
  2284. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2285. return __acquireData(selected, selected.username, clusternodename
  2286. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  2287. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2288. return e; }
  2289. )
  2290. }
  2291. , ownerInstnace(selected) { return __acquireData(selected, selected.username, null
  2292. , selected.instanceName + '-data-' + selected.node_env
  2293. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2294. return e }
  2295. )
  2296. }
  2297. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2298. , commonInstance(selected) { return __acquireData(selected, defaultRepoOwner
  2299. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2300. ) }
  2301. , genericChessInstance(selected) { return __acquireData(selected) }
  2302. }
  2303. })()
  2304. var acquireData = function(slections){
  2305. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2306. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  2307. }
  2308. function reinit(){
  2309. sysAddPathVar('%AppData%\\npm')
  2310. resetgitconfig()
  2311. }
  2312. function init(){
  2313. sysAddPathVar('%AppData%\\npm')
  2314. resetgitconfig()
  2315. }
  2316. function resetgitconfig(){
  2317. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  2318. // Git Credential storage...
  2319. // git config --global credential.helper 'store --file ~/.gitcredentials'
  2320. // git credential-store --file ~/.gitcredentials store
  2321. // // notepad C:/Program Files/Git/etc/gitconfig
  2322. // git config --global --unset credential
  2323. // git config --edit --system
  2324. // git config --global credential.helper "store --file ~/gitcredentials"
  2325. // git credential fill
  2326. // git credential-store --file ~/git.store store
  2327. // Find system git config
  2328. // git config --global --edit
  2329. // git config --list --show-origin
  2330. // git config --list --show-origin --show-scope
  2331. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  2332. // Recipie
  2333. // git config --global --unset credentials.helper
  2334. // cd /path/to/my/repo
  2335. // git config --unset credential.helper
  2336. // git config credential.helper 'store --file ~/.git_repo_credentials'
  2337. // git config credential.*.username my_user_name
  2338. // git config credential.https://gitlab.com.username my_user_name
  2339. // git credential fill
  2340. // git config --global credential.modalprompt false // doesnst work.
  2341. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  2342. var options = {
  2343. inherit: true, shell: true //, env: process.env
  2344. , cwd: instanceroot
  2345. , runas: processedArgs.runas
  2346. }
  2347. var task = ['git', ['config'], options]
  2348. var tasklist = [
  2349. // ['--global', '--unset credentials.helper']
  2350. // ['--unset', 'credentials.helper']
  2351. // ,
  2352. // ['credential.helper', `'store --file git_repo_credentials'`]
  2353. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  2354. , ['--global', '--replace-all', 'user.name', 'pb']
  2355. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  2356. // , ['--list']
  2357. // , ['credential', 'fill']
  2358. ]
  2359. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  2360. var shellT = (args) => { return getgitbashtask(args, onEachError)
  2361. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  2362. }
  2363. execserial(tasklist, task, shellT, onEachError )
  2364. }
  2365. var createTasq = (args, shellT, onEachError) => {
  2366. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  2367. tasq.toString = function(){ return JSON.stringify(args)}
  2368. return tasq;
  2369. }
  2370. var execserial = function(tasklist, task, shellT){
  2371. var exec = (taskArgs)=>{
  2372. var thistask = task.concat();
  2373. thistask[1] = thistask[1].concat()
  2374. thistask[1].push.apply(thistask[1], taskArgs)
  2375. return createTasq(thistask, shellT)
  2376. }
  2377. return any(tasklist.map(exec))
  2378. }
  2379. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  2380. var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) {
  2381. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2382. var errorHandler = (e) => {
  2383. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2384. // console.error('Could not connect to repo server. Timed Out')
  2385. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  2386. if(propValue === 'y') {
  2387. reconfirm = getReconfirmAll()
  2388. return startElxr()
  2389. }
  2390. else if(propValue === 'r'){
  2391. return acquireConfig(selected)
  2392. }
  2393. else process.exit()
  2394. })
  2395. }
  2396. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  2397. var choices = {
  2398. t : `install a new temporary local instance with this name ( will not persist ).
  2399. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2400. , e : 'exit' }
  2401. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2402. choices = utils.assign({
  2403. i : 'create a new instance with this name => will fork the default config under your username'
  2404. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2405. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2406. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2407. , p : 'create a custom config for yourself '
  2408. }, choices)
  2409. }
  2410. return cli.prompt( choices
  2411. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2412. if(propValue === 't') {
  2413. selectedinstance.local = true; return createInstance(selectedinstance)
  2414. }
  2415. if(propValue === 'i') return eNotImplemented()
  2416. if(propValue === 'f') return eNotImplemented()
  2417. if(propValue === 'o') return eNotImplemented()
  2418. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2419. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2420. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2421. else process.exit()
  2422. })
  2423. }
  2424. console.warn(e)
  2425. throw e; //('Config acquisition failed.')
  2426. }
  2427. var successHandler = () => {
  2428. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2429. utils.assign_strict(selectedinstance, require(manifestpath)( null, selectedinstance))
  2430. console.dir(selectedinstance.repos)
  2431. // Config from server always override merges into selection except for the current selection.
  2432. // PB : TODO -- utils.assign Array merges are non-distinct...
  2433. if(!selectedinstance.repos[0].repo) {
  2434. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2435. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2436. }
  2437. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2438. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2439. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2440. }
  2441. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  2442. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2443. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2444. cacheWriteInstanceConfig(chessinstances)
  2445. ENV.NODE_ENV = selectedinstance.node_env;
  2446. }
  2447. return performPull({repo : configrepo}, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2448. .catch( (e)=>{
  2449. // if(e){
  2450. if(Promise.resolve(e) === e) return e;
  2451. // console.error(e)
  2452. e.benign = true;
  2453. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  2454. // }
  2455. })
  2456. }
  2457. var __acquireData = function (selected, owner, clusternodename, datarepo, errHandler) {
  2458. datarepo = datarepo || selected.instanceName + '-data';
  2459. var errorHandler = (e) => {
  2460. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2461. // console.error('Could not connect to repo server. Timed Out')
  2462. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  2463. if(propValue === 'y') {
  2464. reconfirm = getReconfirmAll()
  2465. return startElxr()
  2466. }
  2467. else if(propValue === 'r'){
  2468. return acquireConfig(selected)
  2469. }
  2470. else process.exit()
  2471. })
  2472. }
  2473. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
  2474. var choices = {
  2475. t : `install a temporary local data folder.
  2476. For more options. Request and use a personal username at chess@bbh.org.in )`
  2477. , e : 'exit' }
  2478. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2479. choices = utils.assign({
  2480. i : 'create a new instance with this name => will fork the default config under your username'
  2481. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2482. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2483. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2484. , p : 'create a custom config for yourself '
  2485. }, choices)
  2486. }
  2487. return cli.prompt( choices
  2488. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  2489. if(propValue === 't') {
  2490. selectedinstance.local = true; return createInstanceData(selectedinstance)
  2491. }
  2492. if(propValue === 'i') return eNotImplemented()
  2493. if(propValue === 'f') return eNotImplemented()
  2494. if(propValue === 'o') return eNotImplemented()
  2495. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2496. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2497. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2498. else process.exit()
  2499. })
  2500. }
  2501. console.warn(e)
  2502. throw e; //('Config acquisition failed.')
  2503. }
  2504. var successHandler = () => {
  2505. }
  2506. return performPull({ repo : datarepo }, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2507. .catch( (e)=>{
  2508. // if(e){
  2509. if(Promise.resolve(e) === e) return e;
  2510. // console.error(e)
  2511. e.benign = true;
  2512. throw e; // Not a hard error but we need this for bcontinueonfailure
  2513. // }
  2514. })
  2515. }
  2516. var launchpath = path.resolve(path.normalize(process.env.wd))
  2517. var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  2518. // The easisest would be to ask for a target directory and default to current dir....
  2519. // path.dirname(launchpath).split(path.sep).pop()
  2520. var parent = path.dirname(launchpath);
  2521. var pp = launchpath;
  2522. var instancediscoverytasks = [];
  2523. while(parent !== pp){
  2524. instancediscoverytasks.push(
  2525. ((pa)=>{
  2526. var p = pa;
  2527. return function(){
  2528. return hasElxr(p).then((value)=>{
  2529. if(value) return p
  2530. // PB : TODO -- Using throw like this is not friendly with any...
  2531. throw Object.assign( new Error('Benign Failure in Batch')
  2532. , { value : false, benign : true });
  2533. })
  2534. }
  2535. })(pp)
  2536. )
  2537. pp = parent;
  2538. parent = path.dirname(parent);
  2539. }
  2540. var instanceroot = null
  2541. var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  2542. if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  2543. else instanceroot = ir.pVal
  2544. return instanceroot
  2545. }).catch(()=>{
  2546. instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  2547. })
  2548. // PB : TODO -- Embed this in the build instead of inlining it.
  2549. // Also attepmt to load from ../chess-config/...
  2550. var __default = ((name, options)=>{
  2551. // Default set of users in main repos.
  2552. var users = [
  2553. { username : `${options.username}`, password : `${options.password}` }
  2554. , { username : `chess` }
  2555. // , { username : `baptistdev`, password : 'encrypted' }
  2556. // , { username : `guest`, password : 'encrypted' }
  2557. ]
  2558. // ${options.reposerver} should be used to lookup current config.
  2559. // User can always add more branches and remotes as needed. Mainifest only occupies
  2560. // well defined namespaces
  2561. var remotes = {
  2562. // these are both fetch and push remotes. Use push - remotes to override push.
  2563. 'chess' : {
  2564. server : `${options.reposerver}`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2565. , push : 'no-pushing' }
  2566. , 'baptistdev-public' : {
  2567. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2568. , push : 'no-pushing' }
  2569. // Multiple urls dont tell us the current origin which may be
  2570. // different based on currently available/accessible based on device and client.
  2571. // We just treat them as different remotes and merge as needed.
  2572. //
  2573. , 'origin' : {
  2574. server : `${options.reposerver}`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2575. }
  2576. , 'origin-public' : {
  2577. // export GIT_SSL_NO_VERIFY=true
  2578. server : `https://git.bbh.org.in`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2579. , push : {
  2580. server : `${options.reposerver}`, user : `${options.username}`, path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`}
  2581. }
  2582. }
  2583. , 'origin-unc' : {
  2584. server : `//172.16.0.27/repos`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2585. }
  2586. // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
  2587. }
  2588. // , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
  2589. // We therefore need to use
  2590. // - a pullall
  2591. // - or branch alias for multiple remote branch tracking branch strategy.
  2592. // -- This is however limited to corresponding branch names
  2593. // tracking branches.
  2594. // We at least need one branch for each remote that we wish to track.
  2595. // , 'tracking-branches' : [
  2596. // { master : ['origin/master', 'chess/master'] }
  2597. // ]
  2598. var reposerverinstances = {
  2599. 'http://git.bbh' : { users, remotes }
  2600. , 'https://git.bbh.org.in' : { users, remotes, external : true }
  2601. , '//172.16.0.27/repos' : { users, remotes }
  2602. , 'https://github.com' : {
  2603. // We host a miniaml set of repositories in github.
  2604. get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
  2605. , remotes : {
  2606. 'baptistdev-public' : {
  2607. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2608. , push : 'no-pushing' }
  2609. // , Add other remotes here.
  2610. }
  2611. , external : true, public : true
  2612. }
  2613. }
  2614. return {
  2615. reposervers : Object.keys(reposerverinstances)
  2616. , reposerverinstances
  2617. // Common baseline repos for all chess instances.
  2618. , repos : [
  2619. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  2620. , { repo : 'bbhverse' }
  2621. , { repo : 'clientverse' }
  2622. , { repo : 'serververse' }
  2623. , { repo : 'elxr' }
  2624. , { repo : 'ember-searchable-select' }
  2625. , { repo : 'loopback-component-jsonapi' }
  2626. , { repo : 'loopback-jsonapi-model-serializer' }
  2627. , { repo : 'loopback-connector-mysql' }
  2628. , { repo : 'loopback-connector-ds' }
  2629. , { repo : 'ember-service-worker' }
  2630. , { repo : 'ember-service-worker-asset-cache' }
  2631. , { repo : 'ember-service-worker-cache-fallback' }
  2632. , { repo : 'ember-service-worker-index' }
  2633. , { repo : 'ember-sw-client-route' }
  2634. , { repo : 'global-this' }
  2635. ]
  2636. // Requires elevation only in windows
  2637. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  2638. , exludeMergeRepos : { }
  2639. }
  2640. })(
  2641. '__default' // name
  2642. , { username : 'guest', instanceName : 'chess', node_env : 'development', reposerver : 'https://git.bbh.org.in' } // options
  2643. )
  2644. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2645. // Then acquire and reload and replace this default.
  2646. var hasElxr = function(path, options, cb) {
  2647. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  2648. options = options || {};
  2649. var tasks = [
  2650. '/elxr' // Is there a subfolder named elxr
  2651. , '/elxr/.git' // which is self git repository
  2652. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  2653. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  2654. ]
  2655. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  2656. var value = existsFolderSync(path + tpath);
  2657. return { value, done : acc && !value };
  2658. }).value }
  2659. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  2660. var value = existsFolderSync(path + tpath);
  2661. return { value, done : acc && !value };
  2662. }).value );
  2663. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  2664. var value = existsFolderSync(path + tpath);
  2665. return { value, done : acc && !value };
  2666. }).value);
  2667. }
  2668. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  2669. var detectfromroot = function(root){
  2670. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  2671. }
  2672. var detectLocalInstances = function () {
  2673. console.log(`launchpath = ${launchpath}`)
  2674. console.log(`thisscriptdir = ${thisscriptdir}`)
  2675. // PB : TODO -- !Postpone this.
  2676. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  2677. // Note : Paths should already be normalized fefore this.
  2678. var root = instanceroot;
  2679. var detected = { root };
  2680. var instanceoptions = [clioverrides]
  2681. return hasElxr(launchpath).then( (elxrCliExists) => {
  2682. // We need a reference to the root director for elxr cli to be properly oriented.
  2683. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  2684. // We were run from the proper root with elxr cli in the subfolder.
  2685. instanceroot = root = launchpath;
  2686. instanceoptions.splice( 0, 0, detected = { root })
  2687. instanceoptions.splice( 0, 0, detectfromroot(root))
  2688. }
  2689. else {
  2690. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  2691. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  2692. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  2693. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  2694. instanceroot = root = launchpath;
  2695. instanceoptions.splice( 0, 0, detected = { root })
  2696. instanceoptions.splice( 0, 0, detectfromroot(root))
  2697. }
  2698. else if (launchpath === thisscriptdir) {
  2699. var parentHasElxr = hasElxrSync(launchpath + '/..')
  2700. // PB : TODO -- verify if we have .elxr folder in the parent...
  2701. if(!parentHasElxr) {
  2702. // ! thisscriptdir is not elxr.
  2703. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  2704. }
  2705. // Same directory doesn't mean we are being run from elxr sub directory.
  2706. // In standalone build script we may or not be in the same location.
  2707. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  2708. // Unbuilt therefore we are in the elxr sub directory.
  2709. instanceroot = root = path.normalize(launchpath + '/..');
  2710. instanceoptions.splice( 0, 0, detected = { root });
  2711. instanceoptions.splice( 0, 0, detectfromroot(root));
  2712. }
  2713. else {
  2714. // Built version.
  2715. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  2716. if(parentHasElxr) {
  2717. // Built version was run from the full elxr subfolder. Should work
  2718. // PB : TODO -- but we should switch to the full version...
  2719. instanceroot = root = path.normalize(launchpath + '/..');
  2720. instanceoptions.splice( 0, 0, detected = { root })
  2721. instanceoptions.splice( 0, 0, detectfromroot(root))
  2722. }
  2723. else {
  2724. instanceroot = root = launchpath;
  2725. instanceoptions.splice( 0, 0, detected = { root })
  2726. instanceoptions.splice( 0, 0, detectfromroot(root))
  2727. // Assume current launchpath is a new instance and create.
  2728. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  2729. // if(clioverrides.instanceName) {
  2730. // if(clioverrides.node_env) {
  2731. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  2732. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  2733. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  2734. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  2735. // // eg : floder name can be elixir01 but instance name is elixr
  2736. // }
  2737. // else {
  2738. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  2739. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  2740. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  2741. // }
  2742. // }
  2743. // else {
  2744. // instanceroot = root = launchpath;
  2745. // if(clioverrides.node_env) {
  2746. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  2747. // instanceoptions.splice( 0, 0, detectfromroot(root))
  2748. // }
  2749. // else {
  2750. // // Nothing was specified... We only have one option from root.
  2751. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  2752. // }
  2753. // }
  2754. }
  2755. }
  2756. }
  2757. else {
  2758. if(elxrCliExists) {
  2759. instanceroot = root = launchpath;
  2760. instanceoptions.splice( 0, 0, detected = { root })
  2761. instanceoptions.splice( 0, 0, detectfromroot(root))
  2762. }
  2763. }
  2764. }
  2765. instanceroot = detected.root
  2766. __default.root = root;
  2767. clioverrides.root = clioverrides.root || root;
  2768. // Resolves empty array when No known instances detected.
  2769. return Promise.resolve(instanceoptions)
  2770. })
  2771. }
  2772. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  2773. if(clioverrides.reconfirm) {
  2774. var reconfirm = getReconfirmAll()
  2775. }
  2776. else { var reconfirm = {}; }
  2777. var shouldPrompt = function(k, possiblePrompts, target){
  2778. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  2779. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  2780. || reconfirm[k])
  2781. }
  2782. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  2783. return function(prompts, k, i, a){
  2784. // No local instances config found. We use a default initialized instance available in selectedinstance
  2785. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2786. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2787. if( shouldPrompt(k, possiblePrompts, target) ) {
  2788. delete reconfirm[k];
  2789. // console.log(k)
  2790. // console.dir(possiblePrompts); //console.dir(target)
  2791. prompts.push(async ()=>{
  2792. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  2793. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2794. // var asyncthis = Object.assign(this);
  2795. // By default Latest altered state is provided which is an implicit reference directly.
  2796. promptables[k].choices = choices[k]
  2797. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2798. return await target[k]
  2799. })
  2800. }
  2801. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  2802. return prompts
  2803. }
  2804. }
  2805. var __interactive_prompts = function( target, choices, promptsfilter ){
  2806. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2807. var interactionpoints = {
  2808. runchoice : {
  2809. label :
  2810. `Choose an option :
  2811. d) Install the default chess instance.
  2812. => elxr i chess node_env=development --default
  2813. n) Create your custom new instance interactively
  2814. => elxr i {{instanceName}} node_env={{environment}}
  2815. i) Choose an instance and environment to install
  2816. => elxr i {{instanceName}} node_env={{environment}}
  2817. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2818. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2819. h) Help
  2820. q) Quit
  2821. : `
  2822. , choices : []
  2823. , defaultchoice : 'c'
  2824. , selectedchoice : target.runchoice
  2825. , interpret : function(choice){
  2826. var interpret_map = {
  2827. d : function(){
  2828. processedArgs._[0] = 'i'
  2829. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2830. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2831. target.reposerver = 'https://git.bbh.org.in'
  2832. }
  2833. , n : function() { processedArgs._[0] = 'i' }
  2834. , i : function() {
  2835. processedArgs._[0] = 'i'
  2836. // processedArgs._[1] = target.instanceName || processedArgs._[1] || 'chess';
  2837. }
  2838. , c : async function() {
  2839. // this here will always be the target.
  2840. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2841. label : `Enter cmd :
  2842. p) pull
  2843. Default <= p
  2844. : `
  2845. , defaultchoice : 'pull'
  2846. }
  2847. ));
  2848. var cmd = await target['cmd'];
  2849. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2850. else target['cmd'] = processedArgs._[0] = cmd
  2851. return cmd;
  2852. }
  2853. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2854. , q : function() { process.exit() }
  2855. }
  2856. if(Promise.resolve(choice) === choice){
  2857. return choice.then( resolvedchoice => {
  2858. return (interpret_map[choice] || interpret_map['c']).call(target)
  2859. })
  2860. }
  2861. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(target) )
  2862. // var __interpreter = interpret_map[choice] || interpret_map['c']
  2863. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2864. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2865. // return __interpreter.call(target)
  2866. }
  2867. }
  2868. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  2869. , choices : choices['instanceName'], defaultchoice : 'chess'
  2870. , selectedchoice : target.instanceName
  2871. }
  2872. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  2873. , choices : choices['instanceType'], defaultchoice : 'development'
  2874. , selectedchoice : target.instanceType
  2875. }
  2876. , reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  2877. , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'
  2878. , selectedchoice : target.reposerver
  2879. }
  2880. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  2881. , choices : choices['username'], defaultchoice : 'chess', selectedchoice : target.username } }
  2882. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  2883. , choices : choices['password'], defaultchoice : '***', selectedchoice : target.password } }
  2884. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  2885. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : target.email } }
  2886. }
  2887. function getPromptKeys() {
  2888. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  2889. return promptkeys
  2890. }
  2891. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  2892. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  2893. }
  2894. var downloadsdir = '../Downloads';
  2895. var prerequisites = [
  2896. {
  2897. shellcmd: 'git',
  2898. name : 'git',
  2899. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2900. , installer: 'Git-2.31.0-64-bit.exe'
  2901. , installcmd: ['cmd', ['/c', 'start',
  2902. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2903. , '/VERYSILENT'
  2904. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2905. ]]
  2906. , preinstallsteps: function() {
  2907. var steps = [
  2908. () => {
  2909. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2910. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2911. }
  2912. else return Promise.resolve(true)
  2913. }
  2914. ]
  2915. var prompts = this.getuser(null, ()=>{
  2916. // console.log('preinstallsteps')
  2917. // var gitUser = 'guest';
  2918. // var gitEmail = 'guest@bbh.org.in';
  2919. // var prompts = [];
  2920. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  2921. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  2922. // console.log('prompting in preinstallsteps')
  2923. // return any(prompts).then(()=>{
  2924. // var steps = [
  2925. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2926. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2927. // ]
  2928. // return any(steps.map(getshelltask)).then(() => {
  2929. // })
  2930. // });
  2931. return Promise.resolve(true)
  2932. })
  2933. return any([any(steps), prompts])
  2934. }
  2935. , installsteps: function () {
  2936. return any([this.installcmd].map(getshelltask))
  2937. }
  2938. , postinstallsteps: function(err, users){
  2939. return this.getuser(null, (err, data)=>{
  2940. // ignore err and proceed with data as guest.
  2941. console.dir(data)
  2942. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  2943. return username = data[0];
  2944. }
  2945. data = data || ['guest']
  2946. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2947. console.log('prompting in postinstallsteps')
  2948. var username = 'guest';
  2949. var email = 'guest@bbh.org.in';
  2950. var password = '***';
  2951. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  2952. if(!data.find(e => e === selectedinstance.username)) {
  2953. var steps = [
  2954. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  2955. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  2956. ]
  2957. return any(steps.map(getshelltask)).then(() => {
  2958. })
  2959. }
  2960. else {
  2961. return Promise.resolve(true)
  2962. }
  2963. });
  2964. })
  2965. }
  2966. , install: function () {
  2967. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2968. }
  2969. , verifyAndInstall : function(){
  2970. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2971. if(exists) {
  2972. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2973. return this.postinstallsteps.bind(this)()
  2974. }
  2975. return this.install();
  2976. });
  2977. }
  2978. , getuser : function(repo, onResult){
  2979. var __onResult = onResult || function(e, data){
  2980. data = data || []
  2981. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2982. // console.dir(choices)
  2983. return data[0]
  2984. }
  2985. var globalOrLocal = '--global';
  2986. if(repo) globalOrLocal = '--local'
  2987. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  2988. // not yet configured.
  2989. if(!result.success) return __onResult(result)
  2990. else {
  2991. var users = result.messages[0].trim().split('\n');
  2992. if(users.length === 0 ||
  2993. users.length === 1 && users[0] === 'guest') {
  2994. return __onResult(result)
  2995. }
  2996. else {
  2997. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  2998. }
  2999. })
  3000. .catch((e)=>{
  3001. console.log(e)
  3002. return __onResult(e)
  3003. })
  3004. }
  3005. }
  3006. ,
  3007. {
  3008. shellcmd: 'node',
  3009. name : 'node',
  3010. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  3011. , installer: 'node-v14.16.0-x64.msi'
  3012. , installcmd: ['MSIEXEC.exe', ['/i'
  3013. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  3014. , 'ACCEPT=YES', '/passive']]
  3015. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  3016. }
  3017. ]
  3018. for(var i=0; i<prerequisites.length; i++) {
  3019. prerequisites[prerequisites[i].name] = prerequisites[i];
  3020. }
  3021. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  3022. function ensureDirectoryExistence(filePath) {
  3023. var dirname = path.dirname(filePath);
  3024. if (fs.existsSync(dirname)) {
  3025. return filePath;
  3026. }
  3027. ensureDirectoryExistence(dirname);
  3028. fs.mkdirSync(dirname);
  3029. return filePath;
  3030. }
  3031. var mainTasks = [];
  3032. function verifyAndInstallPrerequisites() {
  3033. var downloadtasks = [];
  3034. var installtasks = [];
  3035. prerequisites.forEach(preq => {
  3036. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  3037. if (exists) console.log(`${preq.shellcmd} exists`)
  3038. else {
  3039. console.log(`${preq.shellcmd} is not installed`)
  3040. return preq.preinstallsteps.call(preq).then(() => {
  3041. installtasks.push(preq.install.bind(preq))
  3042. })
  3043. }
  3044. }))
  3045. })
  3046. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  3047. }
  3048. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  3049. return {
  3050. get (){
  3051. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  3052. var asyncprop = Promise.resolve(propValue)
  3053. if(promptable.interpret){
  3054. asyncprop = promptable.interpret(propValue)
  3055. }
  3056. return asyncprop.then(
  3057. ()=>{
  3058. Object.defineProperty(this, propName, {
  3059. value: propValue,
  3060. writable: true,
  3061. configurable : true,
  3062. enumerable : true
  3063. });
  3064. return propValue
  3065. }
  3066. )
  3067. })
  3068. }
  3069. // , set (propValue){
  3070. // Object.defineProperty(this, propName, {
  3071. // value: propValue,
  3072. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  3073. // configurable : true,
  3074. // enumerable : true
  3075. // })
  3076. // return propValue;
  3077. // }
  3078. , configurable : true
  3079. , enumerable : true
  3080. }
  3081. }
  3082. function acquirelocalinstances(selected){
  3083. // utils.assign is used to cleanup duplicates...
  3084. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  3085. return chessinstances
  3086. }
  3087. function findlocalinstances(chessinstances, instanceoptions){
  3088. // We can expect a .elxr at each level.
  3089. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  3090. earlyreduce( ( value, p, i, a )=>{
  3091. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  3092. if(existsSync( localinstancesPath )) {
  3093. try {
  3094. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  3095. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  3096. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  3097. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  3098. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  3099. return {
  3100. value : chessinstances[instanceName][instanceType]
  3101. , done : true
  3102. };
  3103. }
  3104. })
  3105. })
  3106. }
  3107. catch(e){
  3108. return { }
  3109. }
  3110. }
  3111. else return { }
  3112. }
  3113. )
  3114. }
  3115. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3116. var selectedinstance = { root : process.env.wd };
  3117. var chessinstances = { current_run : {} };
  3118. var promptkeys = {
  3119. cmd : processedArgs._[0] || 'pull'
  3120. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  3121. // 'instanceName' : true
  3122. // , 'node_env' : true
  3123. // , username : ''
  3124. // , runchoice : 'c'
  3125. }
  3126. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  3127. function createLocalChessInstance( cfg ){
  3128. // return createInstance(cfg)
  3129. reconfirm = getReconfirmAll()
  3130. var inst = {};
  3131. var __new = Object.assign({}, __default, cfg)
  3132. inst[cfg.node_env] = __new; return inst;
  3133. }
  3134. var choices = {
  3135. 'instanceName' : []
  3136. , 'reposerver' : []
  3137. , 'instanceType' : []
  3138. , username : ['guest', 'chessdemo', 'demo']
  3139. }
  3140. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  3141. var instances = []
  3142. var reposervers = [];
  3143. var instanceNames = []
  3144. var instanceTypes = ['development', 'production'];
  3145. Object.keys( chessinstances).forEach(instanceName => {
  3146. if(instanceName === 'current_run') return;
  3147. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  3148. var instance = chessinstances[instanceName][node_env];
  3149. reposervers = reposervers.concat(instance.reposervers)
  3150. if(instance.reposerver) reposervers.push(instance.reposerver)
  3151. instances.push(instance)
  3152. instanceTypes.push(instance.node_env)
  3153. instanceNames.push(instance.instanceName)
  3154. })
  3155. })
  3156. instances = instances.concat(detectedinstanceoptions)
  3157. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  3158. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  3159. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  3160. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  3161. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  3162. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  3163. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  3164. }
  3165. var detection_state = {
  3166. localInstanceDetected : false
  3167. }
  3168. const https = require('https')
  3169. const http = require('http');
  3170. const { resolve } = require('path');
  3171. const RESTAPI = (function(){
  3172. // Singleton
  3173. function RESTAPI(){}
  3174. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  3175. // const options = {
  3176. // hostname: 'whatever.com',
  3177. // port: 443,
  3178. // path: '/todos',
  3179. // method: 'POST',
  3180. // headers: {
  3181. // 'Content-Type': 'application/json',
  3182. // 'Content-Length': data.length
  3183. // }
  3184. // }
  3185. RESTAPI.method = function(options, resolve, reject){
  3186. var __method = function() {
  3187. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3188. if(options.payload) {
  3189. const data = new TextEncoder().encode( JSON.stringify(options.payload) )
  3190. options.headers = options.headers || {
  3191. 'Content-Type': 'application/json',
  3192. 'Content-Length': data.length
  3193. }
  3194. }
  3195. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  3196. var acquirer = getHTTPorS(options)
  3197. const req = acquirer.request(options, res => {
  3198. if (res.statusCode < 200 || res.statusCode >= 300) {
  3199. return reject(new Error('statusCode=' + res.statusCode));
  3200. }
  3201. var body = [];
  3202. // res.setEncoding('utf8');
  3203. res.on('data', function(chunk) {
  3204. body.push(chunk);
  3205. });
  3206. res.on('end', function() {
  3207. try {
  3208. body = JSON.parse(Buffer.concat(body).toString());
  3209. } catch(e) {
  3210. reject(e);
  3211. }
  3212. resolve(body);
  3213. });
  3214. });
  3215. req.on('error', error => {
  3216. console.error(error)
  3217. reject(error)
  3218. })
  3219. if(options.payload) req.write(data)
  3220. req.end()
  3221. }
  3222. if(!options.authenticatepost && !usertokens[options.username]) {
  3223. RESTAPI.authenticate(options, function(tokenresp){
  3224. usertokens[options.username] = tokenresp.sha1
  3225. __method(options, resolve, reject)
  3226. },
  3227. function(err){ throw err}
  3228. )
  3229. }
  3230. else __method(options, resolve, reject)
  3231. }
  3232. RESTAPI.post = RESTAPI.method
  3233. var usertokens = {}
  3234. RESTAPI.authenticate = function(options, resolve, reject){
  3235. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3236. if(!usertokens[options.username]) {
  3237. // Authenticate and acquire token.
  3238. // https://git.bbh/api/v1/users/<username>/tokens
  3239. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  3240. var _options = Object.assign({}, options)
  3241. // _options.username = 'demo'
  3242. // _options.password = 'demo123'
  3243. _options.method = 'POST'
  3244. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  3245. _options.path = `/api/v1/users/${_options.username}/tokens`
  3246. _options.authenticatepost = true
  3247. var postoptions = { name : _options.username }
  3248. delete _options.username
  3249. delete _options.password
  3250. _options.payload = postoptions
  3251. RESTAPI.post( _options, function(tokenresp){
  3252. // tokenresp = JSON.parse(tokenresp)
  3253. usertokens[options.username] = tokenresp.sha1
  3254. resolve(tokenresp)
  3255. },
  3256. function(err){ reject(err) }
  3257. )
  3258. }
  3259. else resolve(tokenresp.sha1)
  3260. }
  3261. RESTAPI.get = RESTAPI.post = RESTAPI.method
  3262. return RESTAPI
  3263. })();
  3264. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  3265. const GITEA = (function(){
  3266. function GITEA(){}
  3267. GITEA.repository = {
  3268. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3269. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  3270. // giteaoptions = {
  3271. // organization string
  3272. // --- organization name, if forking into an organization
  3273. // }
  3274. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  3275. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  3276. httpoptions.method = 'POST'
  3277. httpoptions.payload = giteaoptions;
  3278. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3279. }
  3280. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3281. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  3282. httpoptions.method = 'PATCH'
  3283. httpoptions.payload = giteaoptions;
  3284. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3285. }
  3286. }
  3287. GITEA.user = {
  3288. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3289. // ​/users​/{username} // Get a user
  3290. httpoptions.path = `/api/v1/users/${httpoptions.username}`
  3291. httpoptions.method = 'GET'
  3292. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  3293. }
  3294. }
  3295. return GITEA
  3296. })();
  3297. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  3298. const GIT = (function(){
  3299. function GIT(){}
  3300. Object.assign(GIT, {
  3301. 'switch user'(username){
  3302. var server = new URL(selectedinstance.reposerver);
  3303. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  3304. , username : selectedinstance.username, password : selectedinstance.password
  3305. }).then(()=>{
  3306. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  3307. {
  3308. inherit: true, shell: true,
  3309. env: process.env
  3310. , cwd: instanceroot + '/' + repo
  3311. , runas: processedArgs.runas
  3312. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  3313. })
  3314. }
  3315. )
  3316. .catch(e => {
  3317. console.error(e + 'Could not switch. Probably no such user.')
  3318. })
  3319. }
  3320. })
  3321. return GIT
  3322. })();
  3323. function createInstanceData(target, source) {
  3324. var sourceinstance = source || target;
  3325. console.dir(sourceinstance)
  3326. var args = {
  3327. remotebase : sourceinstance.reposerver + '/chess/'
  3328. , sourcerepo : sourceinstance.repo || 'chess-data'
  3329. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3330. }
  3331. if(sourceinstance.local) {
  3332. var options = {
  3333. inherit: true, shell: true,
  3334. env: process.env
  3335. , cwd : instanceroot
  3336. , runas: processedArgs.runas
  3337. }
  3338. var cmdseq = [
  3339. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3340. ]
  3341. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3342. }
  3343. else {
  3344. // http://try.gitea.io/api/v1/org/{org}/repos
  3345. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3346. throw 'createInstanceData is possible only within the same repository server.'
  3347. }
  3348. var server = new URL(target.reposerver);
  3349. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3350. , username : target.username, password : target.password
  3351. }
  3352. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3353. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3354. return GITEA.repository.updateattributes( {
  3355. hostname : server.host, protocol : server.protocol
  3356. , username : target.username, password : target.password
  3357. }
  3358. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3359. , { name : `${args.targetrepo}`}
  3360. )
  3361. }
  3362. )
  3363. }
  3364. // GITEA.repository.updateattributes( {
  3365. // hostname : server.host, protocol : server.protocol
  3366. // , username : selectedinstance.username, password : selectedinstance.password
  3367. // }
  3368. // , { repo : `chess-config`, owner : selectedinstance.username }
  3369. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3370. // )
  3371. // return selectedinstance
  3372. }
  3373. function createInstance(target, source) {
  3374. var sourceinstance = source || target;
  3375. console.dir(sourceinstance)
  3376. var args = {
  3377. remotebase : sourceinstance.reposerver + '/chess/'
  3378. , sourcerepo : sourceinstance.repo || 'chess-config'
  3379. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3380. }
  3381. if(sourceinstance.local) {
  3382. var options = {
  3383. inherit: true, shell: true,
  3384. env: process.env
  3385. , cwd : instanceroot
  3386. , runas: processedArgs.runas
  3387. }
  3388. var cmdseq = [
  3389. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3390. ]
  3391. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3392. }
  3393. else {
  3394. // http://try.gitea.io/api/v1/org/{org}/repos
  3395. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3396. throw 'createInstance is possible only within the same repository server.'
  3397. }
  3398. var server = new URL(target.reposerver);
  3399. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3400. , username : target.username, password : target.password
  3401. }
  3402. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3403. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3404. return GITEA.repository.updateattributes( {
  3405. hostname : server.host, protocol : server.protocol
  3406. , username : target.username, password : target.password
  3407. }
  3408. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3409. , { name : `${args.targetrepo}`}
  3410. )
  3411. }
  3412. )
  3413. }
  3414. // GITEA.repository.updateattributes( {
  3415. // hostname : server.host, protocol : server.protocol
  3416. // , username : selectedinstance.username, password : selectedinstance.password
  3417. // }
  3418. // , { repo : `chess-config`, owner : selectedinstance.username }
  3419. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3420. // )
  3421. // return selectedinstance
  3422. }
  3423. var skipprerequisites = false;
  3424. function initinstances(selected_overrides) {
  3425. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  3426. var instanceName = selected_overrides.instanceName
  3427. || clioverrides.instanceName
  3428. // || processedArgs._[1]
  3429. || chessinstances.current_run.instanceName
  3430. var node_env = selected_overrides.node_env
  3431. || clioverrides.node_env
  3432. // || processedArgs.node_env
  3433. || chessinstances.current_run.node_env
  3434. var reposerver = selected_overrides.reposerver
  3435. || clioverrides.reposerver
  3436. // || processedArgs.node_env
  3437. || chessinstances.current_run.reposerver
  3438. if(!instanceName) {
  3439. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  3440. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3441. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3442. }
  3443. if(!node_env) {
  3444. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3445. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3446. }
  3447. if(!reposerver) {
  3448. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3449. }
  3450. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  3451. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  3452. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  3453. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  3454. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  3455. }
  3456. // Override sequence.
  3457. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  3458. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  3459. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  3460. if(selected_overrides.node_env === undefined) delete selected_overrides.node_env
  3461. selectedinstance = utils.assign(
  3462. chessinstances[instanceName][node_env]
  3463. , clioverrides
  3464. , selected_overrides
  3465. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  3466. );
  3467. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  3468. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  3469. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  3470. // // Brand New.
  3471. // selectedinstance = Object.assign( __default, selectedinstance )
  3472. // }
  3473. if(!selectedinstance.repos[0].repo) {
  3474. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3475. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3476. }
  3477. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  3478. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3479. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3480. }
  3481. // Config from server always override merges into selection except for the current selection.
  3482. // PB : TODO -- utils.assign Array merges are non-distinct...
  3483. chessinstances[instanceName][node_env] = selectedinstance;
  3484. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3485. cacheWriteInstanceConfig(chessinstances)
  3486. // PB : TODO -- We should probably write the new server config also...
  3487. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3488. return chessinstances
  3489. }
  3490. var skipprereqs = {}
  3491. var maintask = () => {
  3492. // Default cmd to run !
  3493. processedArgs._[0] === processedArgs._[0] || 'pull';
  3494. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  3495. if(!noprerequisites[processedArgs._[0]]
  3496. && !skipprereqs[processedArgs._[0]]
  3497. ) {
  3498. return prerequisites.git.verifyAndInstall().then(()=>{
  3499. var e = { message : 'verifyAndInstall', success : true}
  3500. var inittasks = []
  3501. var commontask = () => { preworkerconfig(); return elxrworker(true) }
  3502. if(!detection_state.localInstanceDetected) {
  3503. var t1 = ()=>{ return createInstance(selectedinstance) };
  3504. t1.statuslog = statuslog
  3505. var specifictask = shell_verse.getNonElevatedTask(t1)
  3506. }
  3507. else {
  3508. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  3509. t2.statuslog = statuslog
  3510. var specifictask = shell_verse.getNonElevatedTask(t2)
  3511. }
  3512. inittasks.push( specifictask().catch((err) => {
  3513. e = err;
  3514. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  3515. console.error(err)
  3516. }).then( commontask )
  3517. // .finally(()=>{
  3518. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  3519. // if(!e.success) fs.writeFileSync('run.done', 'error');
  3520. // // return process.exit()
  3521. // }))
  3522. )
  3523. return any(inittasks)
  3524. })
  3525. }
  3526. else {
  3527. console.log('cmd has no preqs or has been configured to skip preqs')
  3528. preworkerconfig()
  3529. return elxrworker()
  3530. }
  3531. }
  3532. function generateDependencies(){
  3533. // PB : TODO -- Keep only the last n runs...
  3534. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3535. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3536. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  3537. // PB : TODO include and build from files... using rollup..
  3538. var downloadbatch =
  3539. `::**************************************************************************
  3540. :Download_ <url> <File>
  3541. Powershell.exe ^
  3542. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  3543. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  3544. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  3545. exit /b
  3546. ::**************************************************************************`
  3547. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  3548. var windowselevate =
  3549. `
  3550. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  3551. <script language="vbscript">
  3552. document.title = "elxr control panel"
  3553. self.ResizeTo 200,600
  3554. Sub Window_Onload
  3555. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  3556. End Sub
  3557. Set objShell = CreateObject("WScript.Shell")
  3558. Set objENV = objShell.Environment("Process")
  3559. dim NODE_ENV
  3560. NODE_ENV = objENV("NODE_ENV")
  3561. </script>
  3562. <script language="javascript">
  3563. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  3564. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  3565. // alert(windowselevate.commandLine)
  3566. var args = windowselevate.commandLine.split('"').slice(3);
  3567. // alert(args)
  3568. var processedArgs = { _ : [] }
  3569. var namedArgs = [];
  3570. namedArgs.push('--wd=' + objENV('wd'))
  3571. // alert(namedArgs)
  3572. for(var item in args){
  3573. if(args[item].charAt(0) === '-'){
  3574. namedArgs.push(args[item])
  3575. var split = args[item].split('=');
  3576. processedArgs[split[0].slice(2)] = split[1] || true;
  3577. }
  3578. else processedArgs._.push(args[item]);
  3579. }
  3580. // args = args.forEach(function(item){ })
  3581. // alert('processedArgs._ : ' + processedArgs._);
  3582. // alert(processedArgs.runas);
  3583. // alert(objENV('wd'))
  3584. // PB : TODO -- Convert all the cli args back to string.
  3585. // __filename will sure we are launhed using the same entry point.
  3586. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  3587. var shell = new ActiveXObject('shell.application');
  3588. // alert('launching node privilged. ' + processedArgs['nodepath'])
  3589. // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
  3590. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  3591. // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
  3592. // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
  3593. shell.ShellExecute('node', cargs, '', 'runas', 1);
  3594. // alert('/k node ' + cargs + '')
  3595. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  3596. var fso = new ActiveXObject('Scripting.FileSystemObject');
  3597. window.onload = function() {
  3598. document.body.style.backgroundColor = 'black';
  3599. document.body.style.fontFamily = 'arial';
  3600. var log = document.createElement('div');
  3601. log.innerHTML='Please Wait';
  3602. function l(msg){ log.innerHTML+= msg; };
  3603. log.style.color = 'blue';
  3604. log.style.width = '95%';
  3605. log.id = 'log';
  3606. document.body.appendChild(log);
  3607. l('<Br/>Current config : ')
  3608. l('<Br/>NODE_ENV = ' + NODE_ENV)
  3609. l('<Br/>cmd = ' + processedArgs._[0])
  3610. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  3611. l('<Br/><Br/>')
  3612. var timer = function(){
  3613. l('.');
  3614. if(fso.FileExists("run.done")) close();
  3615. else window.setTimeout(timer, 1000);
  3616. };
  3617. window.setTimeout(timer, 3000);
  3618. };
  3619. </script>
  3620. </html>
  3621. `
  3622. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  3623. }
  3624. var startElxr = function() {
  3625. const retaincount = 2
  3626. var min = runtimestamp;
  3627. var collect = []
  3628. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  3629. reconfirm = getReconfirmAll()
  3630. }
  3631. return detectLocalInstances().then((detectedinstanceoptions)=>{
  3632. detectedinstanceoptions.splice(0,0, __default)
  3633. var cmdinstance = cmds[clioverrides.cmd]
  3634. var cmdprompts = cmdinstance.getPossiblePrompts()
  3635. selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  3636. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  3637. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2), promptkeys )
  3638. // promptkeys = utils.assign(promptkeys, clioverrides)
  3639. if(cmdprompts.instanceName) {
  3640. // not an instanceless cmd.
  3641. console.dir(selectedinstance)
  3642. try {
  3643. chessinstances = acquirelocalinstances(selectedinstance);
  3644. findlocalinstances(chessinstances, detectedinstanceoptions)
  3645. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  3646. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3647. var inst = initinstances(selectedinstance)
  3648. detection_state.localInstanceDetected = true;
  3649. return inst;
  3650. })
  3651. }
  3652. catch (e) {
  3653. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  3654. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3655. return initinstances(selectedinstance)
  3656. })
  3657. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  3658. // // Weve not been told what to do.
  3659. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  3660. // }
  3661. todo = todo.then(() => {
  3662. try {
  3663. chessinstances = acquirelocalinstances(selectedinstance)
  3664. findlocalinstances(chessinstances, detectedinstanceoptions)
  3665. detectedinstanceoptions.splice(0,0, __default)
  3666. initinstances(selectedinstance)
  3667. detection_state.localInstanceDetected = true;
  3668. }
  3669. catch (e) {
  3670. // console.error(e)
  3671. console.log('No local instances config found in current root = ' + selectedinstance.root);
  3672. console.log('A config will be createed with the instance and environment chosen...')
  3673. // return (async ()=>{return await __default.reposerver})().then(()=>{
  3674. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  3675. // return selectedinstance = Object.assign(__default, selectedinstance);
  3676. // })
  3677. detection_state.localInstanceDetected = false;
  3678. return selectedinstance
  3679. }
  3680. })
  3681. }
  3682. return todo
  3683. }
  3684. else return Promise.resolve(true)
  3685. })
  3686. .then(()=>{
  3687. generateDependencies();
  3688. if(noprerequisites[processedArgs._[0]]
  3689. || skipprereqs[processedArgs._[0]]
  3690. ) {
  3691. return elxrworker()
  3692. }
  3693. var neTask = ()=>{
  3694. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  3695. // collect garbage
  3696. return dirs( (dir)=>{
  3697. var matches = /run-(.*)/gm.exec(dir.name)
  3698. if(matches) {
  3699. if(+(matches[1]) < min) {
  3700. min = matches[1]
  3701. collect.splice( 0, 0, matches[1] )
  3702. }
  3703. else collect.push(matches[1])
  3704. }
  3705. }, `${selectedinstance.root}/.elxr` )
  3706. .then(()=>{
  3707. // delete garbage
  3708. if(collect.length > retaincount) {
  3709. var asyncs = [];
  3710. while((collect.length - asyncs.length) > retaincount) {
  3711. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  3712. }
  3713. return Promise.all(asyncs)
  3714. }
  3715. else return true
  3716. })
  3717. }
  3718. neTask.statuslog = statuslog
  3719. shell_verse.getNonElevatedTask( neTask )()
  3720. var commonTask = ()=>{
  3721. verifyAndInstallPrerequisites.statuslog = statuslog
  3722. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  3723. mainTasks.push(maintask)
  3724. return any(mainTasks);
  3725. }
  3726. return commonTask()
  3727. })
  3728. }
  3729. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  3730. // -- Currently workaround in windows is to always run from a non-elevated shell.
  3731. shell_verse.acquireElevationState().then((elevationstate) => {
  3732. return detectInstanceRoot.then(()=>{
  3733. var cmdobj = cmds[clioverrides.cmd]
  3734. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  3735. if(cmdobj.independentcmd) {
  3736. if(cmdobj.requiresElevation) {
  3737. return cmdobj.cmdFn()
  3738. }
  3739. else return cmdobj.cmdFn()
  3740. }
  3741. else return startElxr()
  3742. })
  3743. .catch(e => {
  3744. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  3745. else console.log('error : ' + e)
  3746. })
  3747. })
  3748. })
  3749. // .then( () => {
  3750. // console.log(process._getActiveHandles());
  3751. // console.log(process._getActiveRequests());
  3752. // })
  3753. // detect if alread installed -> Take no action.
  3754. // download if no installer avalable -> next()
  3755. // install
  3756. function chackandinstall(items) {
  3757. var tasks = []
  3758. items.forEach(item => {
  3759. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  3760. })
  3761. return Promise.all(tasks).then(existances => {
  3762. existances.forEach((exists, i) => {
  3763. if (!exists) {
  3764. return downloadandinstall([items[i]])
  3765. }
  3766. })
  3767. })
  3768. }
  3769. function downloadandinstall(items) {
  3770. var tasks = []
  3771. items.forEach(item => {
  3772. tasks.push(getTaskDownload(item))
  3773. })
  3774. return Promise.all(tasks)
  3775. }
  3776. // Sample instances config.
  3777. // var instances = {
  3778. // "elixir": {
  3779. // "production": {
  3780. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  3781. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  3782. // , "exludeMergeRepos": {
  3783. // "elixir-config-development": true, "elixir-config-test": true
  3784. // , "elixir-config-production": true, "elixir-data": true
  3785. // }
  3786. // , "instanceName": "elixir", "node_env": "production"
  3787. // }
  3788. // },
  3789. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  3790. // }
  3791. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...