Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
4 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
6 дней назад
1 неделю назад
6 дней назад
2 лет назад
3 лет назад
1 год назад
4 лет назад
2 лет назад
1 год назад
5 дней назад
2 лет назад
1 год назад
2 лет назад
3 лет назад
1 год назад
6 дней назад
1 год назад
6 дней назад
2 лет назад
2 лет назад
2 лет назад
6 дней назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
6 дней назад
2 лет назад
1 год назад
2 лет назад
1 год назад
2 недель назад
1 год назад
6 дней назад
1 год назад
2 лет назад
2 лет назад
1 год назад
1 год назад
2 лет назад
2 лет назад
1 год назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
6 дней назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
1 год назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
2 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
6 дней назад
2 недель назад
6 дней назад
2 недель назад
6 дней назад
2 недель назад
1 год назад
2 недель назад
1 год назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
3 лет назад
2 недель назад
3 лет назад
2 недель назад
6 дней назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
4 лет назад
2 недель назад
2 недель назад
4 лет назад
2 недель назад
4 лет назад
2 недель назад
2 лет назад
2 недель назад
4 лет назад
2 недель назад
2 лет назад
2 недель назад
4 лет назад
2 недель назад
3 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
1 год назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
6 дней назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
2 недель назад
3 недель назад
1 год назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
1 год назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 лет назад
2 недель назад
2 недель назад
2 недель назад
2 недель назад
2 лет назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
3 лет назад
2 недель назад
2 недель назад
2 недель назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
2 недель назад
2 недель назад
4 лет назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
6 дней назад
2 недель назад
1 год назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
4 лет назад
2 лет назад
2 недель назад
6 дней назад
2 недель назад
2 лет назад
2 недель назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
6 лет назад
2 недель назад
3 лет назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
3 лет назад
2 недель назад
3 лет назад
2 недель назад
3 лет назад
2 недель назад
2 лет назад
2 недель назад
3 лет назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
3 лет назад
2 лет назад
2 недель назад
3 лет назад
2 недель назад
2 недель назад
3 недель назад
2 недель назад
2 недель назад
2 лет назад
2 недель назад
2 недель назад
2 недель назад
2 лет назад
2 недель назад
2 недель назад
2 недель назад
3 недель назад
3 лет назад
2 недель назад
3 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
2 недель назад
3 лет назад
2 недель назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
3 недель назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 недель назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 недель назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
1 год назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
1 год назад
2 лет назад
1 год назад
2 лет назад
1 год назад
2 лет назад
3 лет назад
2 лет назад
1 год назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
1 год назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
2 лет назад
3 лет назад
4 лет назад
3 лет назад
3 лет назад
3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042
  1. 
  2. // {{!-- https://corporatefinanceinstitute.com/resources/knowledge/accounting/general-ledger-gl/ --}}
  3. "use strict";
  4. // console.log([ 'If this is colorized we have color output...' ])
  5. // console.dir(process.env)
  6. var __g = require('global-this');
  7. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  8. __g.env = ENV
  9. ENV.NODE_ENV = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  10. const fs = require('fs')
  11. var path = require('path');
  12. var utils = require('bbhverse');
  13. var any = utils.any;
  14. var Tasq = utils.Tasq
  15. var statuslog = utils.Traq
  16. var Traq = utils.Traq
  17. // console.error('EEEEEEEEEEEEEEEEEEEE')
  18. var util = require('util')
  19. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  20. var cli = require('./cliverse')
  21. var nodeShellExec = cli.nodeShellExec;
  22. const cliargs = utils.cliargs;
  23. const processedArgs = cliargs(process.argv.slice(2));
  24. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  25. // var shell_verse = cli.shell_verse;
  26. // const getVersion = cli.shell_verse.getVersion
  27. function isWin(){ return /^win/.test(process.platform) }
  28. try {
  29. if(isWin()) {
  30. var win_verse = require('./win_verse')
  31. var shell_verse = win_verse;
  32. }
  33. else {
  34. var lin_verse = require('./lin_verse')
  35. var shell_verse = lin_verse;
  36. }
  37. }
  38. catch(e) {
  39. console.dir(e);
  40. console.error('cli environment detection failed')
  41. }
  42. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  43. shell_verse.getVersion = function getVersion() { return BUILD_VERSION; }
  44. const runtimestamp = processedArgs.runtimestamp ? (new Date(processedArgs.runtimestamp)).getTime() : (new Date()).getTime();
  45. var defaultowner = 'chess';
  46. // 'use strict';
  47. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  48. // PB : TODO --
  49. // runas bypass non elevated tasks when we request privelege
  50. // runas message is always error needs to be fixed.
  51. // runas wait needs to be parallelized.
  52. // suppress elevation check error messages
  53. // support runas lauched directly from shell.
  54. // pass in environment in hta to shellexecute.
  55. const https = require('https')
  56. const http = require('http');
  57. const { Console } = require('console');
  58. const { env } = require('process');
  59. const { validate } = require('uuid');
  60. var core = utils.core(0)
  61. const PATTERNAPI = core.PATTERNAPI
  62. // const RESTAPI = require('serververse').RESTAPI
  63. const RESTAPI = (function(){
  64. // Singleton
  65. function RESTAPI(){}
  66. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  67. // const httpsoptions = {
  68. // hostname: 'whatever.com',
  69. // port: 443,
  70. // path: '/todos',
  71. // method: 'POST',
  72. // headers: {
  73. // 'Content-Type': 'application/json',
  74. // 'Content-Length': data.length
  75. // }
  76. // }
  77. RESTAPI.method = function(options, resolve, reject){
  78. options.headers = options.headers || { 'Content-Type': 'application/json' }
  79. const data = options.payload ? new TextEncoder().encode( JSON.stringify(options.payload) ) : null
  80. options.headers = options.payload ? (options.headers || {
  81. 'Content-Type': 'application/json',
  82. 'Content-Length': data.length
  83. }) : (options.headers || {})
  84. !options.headers.Authorization && usertokens[options.username] ? (()=>{
  85. options.headers.Authorization = `token ${usertokens[options.username]}`
  86. delete options.username
  87. onauthenticated()
  88. })() : (()=>{
  89. if(!usertokens[options.username] && !options.isAuthCall) {
  90. RESTAPI.authenticate( utils.assign( {isAuthCall : true}, options ) , onauthenticated, function(err){
  91. // PB : TODO -- Retry without auth...
  92. console.error('Auth failed or not accessible')
  93. reject(err)
  94. })
  95. }
  96. else onauthenticated()
  97. })()
  98. function onauthenticated(){
  99. var acquirer = getHTTPorS(options)
  100. const req = acquirer.request(options, res => {
  101. if (res.statusCode < 200 || res.statusCode >= 300) {
  102. // new Error('statusCode=' + res.statusCode)
  103. return reject('statusCode = ' + res.statusCode);
  104. }
  105. var body = [];
  106. // res.setEncoding('utf8');
  107. res.on('data', (chunk)=>{ body.push(chunk); });
  108. res.on('end', ()=>{
  109. try {
  110. if(res.headers['content-type'] && res.headers['content-type'].split(';').find( (i)=> i.trim() === 'application/json' )) body = JSON.parse(Buffer.concat(body).toString());
  111. else body = Buffer.concat(body).toString();
  112. } catch(e) { return reject(e); }
  113. resolve(body);
  114. });
  115. });
  116. req.on('error', error => { reject(error) })
  117. if(options.payload) req.write(data)
  118. req.end()
  119. }
  120. }
  121. var usertokens = {}
  122. RESTAPI.authenticate = function(options, resolve, reject){
  123. options.headers = options.headers || { 'Content-Type': 'application/json' }
  124. if(!usertokens[options.username]) {
  125. // Authenticate and acquire token.
  126. // https://git.bbh/api/v1/users/<username>/tokens
  127. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  128. var _options = Object.assign({}, options)
  129. // _options.username = 'demo'
  130. // _options.password = 'demo123'
  131. _options.method = 'POST'
  132. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  133. _options.path = `/api/v1/users/${_options.username}/tokens`
  134. var postoptions = { name : _options.username }
  135. delete _options.username
  136. delete _options.password
  137. _options.payload = postoptions
  138. RESTAPI.post( _options, function(tokenresp){
  139. // tokenresp = JSON.parse(tokenresp)
  140. usertokens[options.username] = tokenresp.sha1
  141. resolve(tokenresp)
  142. },
  143. function(err){ reject(err) }
  144. )
  145. }
  146. else resolve(tokenresp.sha1)
  147. }
  148. RESTAPI.put = RESTAPI.get = RESTAPI.post = RESTAPI.method
  149. return RESTAPI
  150. })();
  151. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  152. const ARGUMENTVALIDATOR = (function(){
  153. const ARGUMENTVALIDATOR = function(){}
  154. ARGUMENTVALIDATOR.validate = function( tovalidate, assertions, exclusions, defaults ) {
  155. exclusions = exclusions || {}
  156. defaults = defaults || {}
  157. // PB : TOOD assertions should have a value enforcement validation. Either as list or pattern or range... etc...
  158. // At a minimum assertions will require a presence of the key.
  159. // PB : TODO -- review arraymergetype ARRAY MERGE TYPES...
  160. // -- array -> value should promote the value to array with a distinct insert...
  161. // -- value -> array behaviour should result in a distinct insert into the array.
  162. // -- array -> array should result in a DISTINCT UNION.
  163. tovalidate = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, defaults, tovalidate );
  164. var validator = function(v, mv){
  165. // Assertions, Exclusions and Defaults have the following structure for each keyed value.
  166. // TOP level value true Eg : assertions[key] === true
  167. // TOP level value is a primitive Eg : assertions[key] === 5125
  168. // TOP level value is a primitive Eg : assertions[key] === "5125"
  169. // TOP level value is a regexp pattern Eg : assertions[key] === /\t5125.*/
  170. // TOP level value is an array
  171. // LHS can be an array in which case each value one level lower is matched to the assertions.
  172. // Array equality (===) is meaningless. Specially since the instance value is an actualized value the the assertions are a pattern.
  173. // They can therefore only be compared internal primitive value equivalence via a pattern.
  174. // in which case the following structure is expected for assertions, exclusions and defaults
  175. /* Eg : assertions[key] === [
  176. // A top level array of a list of choices
  177. // A second level list of primitive rules, values, functions and regex patterns where all rules must match
  178. [ /\t5125XXXXX/, /\s\d\d125XXX.*X/ ] // These rules can be collapsed into more optimal sets... but the user is free to define any such rules.
  179. , [5125]
  180. , ["5125"]
  181. , [ /\t5125XXXXX/, [ a, b, c ] ]
  182. ]
  183. // Any value can be replaced with a 2 level array. 1st level is a list of options/choices [OR assertions], second level is a list of all that should match [AND assertions]
  184. */
  185. // TOP level value is an object. LHS also must be an object. All values can have array substitutions in RHS.
  186. const typegroupValidators = {
  187. '[Primitive]' : function(v, mv){
  188. var nt = utils.js.nativeType(mv)
  189. // console.dir(nt)
  190. // console.log('------------------')
  191. if(nt !== '[object Boolean]') return mv === v
  192. else {
  193. return typeValidators[nt](v, mv)}
  194. }
  195. , 'undefined' : function(v, mv){
  196. // , '[Null]'
  197. // , '[Undefined]'
  198. // , '[Symbol]'
  199. // , '[Array]'
  200. // , '[Object]'
  201. // , '[Special]' and other newly defined typegroups
  202. return typeValidators[utils.js.nativeType(mv)](v, mv)
  203. }
  204. }
  205. const typeValidators = {
  206. '[object Function]' : function(v, mv){ return mv(v) }
  207. , '[object RegExp]' : function(v, mv) {
  208. if(mv.g || mv.m) throw 'MULTINLINE and GLOBAL MULTIPLE OCCURENCES NOT YET SUPPORTED'
  209. return mv.exec(v)
  210. } // PB : TODO -- multiple regexp matches and other criterion in terms of count of exact occurences etc.. one many etc.
  211. // , '[object Array]' : arraysome
  212. // , '[object Array All Or None]' : arrayall
  213. , 'arrayany' : function(v, mv){
  214. // Any one assertion should match in top level
  215. for(var tm in mv ) {
  216. if(utils.js.nativeType(mv) === ['[object Array]'] && typeValidators['[object Array All Or None]'](v, mv)) return true
  217. else if(typegroupValidators[utils.js.typeGroup(mv)](v, mv)) return true
  218. }
  219. }
  220. , 'arrayall' : function(v, mv) {
  221. // All should match in next level
  222. for(var tm in mv ) {
  223. // if(utils.js.nativeType(mv) === ['[object Array]']) return typegroupValidators[utils.js.typeGroup(mv)](v, mv)
  224. // else return typegroupValidators[utils.js.typeGroup(mv)](v, mv)
  225. if(!typegroupValidators[utils.js.typeGroup(mv)](v, mv)) return false
  226. }
  227. return true
  228. }
  229. , '[object Symbol]' : function(v, mv) { throw "SYMBOL VALIDATOR NOT YET IMPLEMENTED" }
  230. , '[object Boolean]' : function(v, mv) {
  231. // console.dir('typeValidators Boolean')
  232. // console.log(`${v} ${mv}` )
  233. if(mv === true && v === undefined ) { throw `for ${key} value is required but received ${v}` }
  234. else return true
  235. }
  236. , 'undefined' : function(v, mv){ return mv === v } // PB : TODO -- wont work for symbol...
  237. }
  238. // For arrays we also need to validate position, sequence, count etc. etc..
  239. typeValidators['[object Array]'] = typeValidators.arrayany
  240. typeValidators['[object Array All Or None]'] = typeValidators.arrayall
  241. return typegroupValidators[utils.js.typeGroup(mv)](v, mv)
  242. };
  243. Object.keys(assertions).forEach( key => {
  244. if( tovalidate[key] === undefined && assertions[key]) throw `Improper value for ${key} property value must be present`
  245. if(!validator( tovalidate[key], assertions[key] )) throw `Improper value ${tovalidate[key]} for ${key} value should be like ${JSON.stringify(assertions[key])}`
  246. // if( assertions[key] !== tovalidate[key] ) {
  247. // if(assertions[key] !== true) {
  248. // // there is some actual value to qualify.
  249. // if ( utils.js.isArray(tovalidate[key]) ) {
  250. // tovalidate[key].forEach( v => validator( v, assertions[key] ) )
  251. // // Each value may need to be qualified !!! and ??? how deep ??? maybe only the top one... type and pattern and value...
  252. // }
  253. // else validator( tovalidate[key], assertions[key] )
  254. // }
  255. // // else simple presence check worked not value qualifiers provided.
  256. // }
  257. // // else there is an exact value match...
  258. })
  259. Object.keys(exclusions).forEach( key => {
  260. if(tovalidate[key] && exclusions[key] ) throw `ARGUMENTVALIDATOR Improper value for ${key} property must value not be present. `
  261. if(validator( tovalidate[key], exclusions[key] )) throw `ARGUMENTVALIDATOR Improper value ${tovalidate[key]} for ${key} varlue should be like ${JSON.stringify(assertions[key])}`
  262. // if( exclusions[key] !== tovalidate[key] ) {
  263. // if(exclusions[key] !== true) {
  264. // if ( utils.js.isArray(tovalidate[key]) ) {
  265. // tovalidate[key].forEach( v => validator.call({exclusions:true}, v, exclusions[key]) )
  266. // // Each value may need to be qualified !!! and ??? how deep ??? maybe only the top one... type and pattern and value...
  267. // }
  268. // else validator.call({exclusions:true}, tovalidate[key], exclusions[key] )
  269. // throw "VALUE QUALIFICATOIN NOT YET IMPLEMENTED"
  270. // }
  271. // // else simple presence check worked not value qualifiers provided.
  272. // }
  273. // // else there is an exact value match...
  274. })
  275. return tovalidate
  276. }
  277. return ARGUMENTVALIDATOR
  278. })()
  279. const GITEA = (function(){
  280. function GITEA(){}
  281. GITEA.APIROOT = '/api/v1'
  282. GITEA.repository = {
  283. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  284. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  285. // giteaoptions = {
  286. // organization string
  287. // --- organization name, if forking into an organization
  288. // }
  289. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  290. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  291. httpoptions.method = 'POST'
  292. httpoptions.payload = giteaoptions;
  293. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  294. }
  295. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  296. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  297. httpoptions.method = 'PATCH'
  298. httpoptions.payload = giteaoptions;
  299. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  300. }
  301. , exists( httpoptions, repo, owner ) {
  302. // ​/users​/{username} // Get a user
  303. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repo}`
  304. httpoptions.method = 'GET'
  305. return new Promise( (resolve, reject) => {
  306. RESTAPI.get(httpoptions, function(o){
  307. if(o.id) return resolve(true)
  308. return resolve(false) }, reject || function(){ return false } )
  309. })
  310. }
  311. , addcollaborator( httpoptions, repodef, owner, collaborator, permission ) {
  312. permission = permission || 'Read'
  313. httpoptions.payload = { permission }
  314. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repodef.repo}/collaborators/${collaborator}`
  315. httpoptions.method = 'PUT'
  316. return new Promise( (resolve, reject) => {
  317. RESTAPI.put(httpoptions, function(o){
  318. //
  319. if(o === "") return resolve(true)
  320. return resolve(false) }, reject || function(){ return false } )
  321. })
  322. }
  323. }
  324. GITEA.user = {
  325. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  326. // ​/users​/{username} // Get a user
  327. httpoptions.path = `${GITEA.APIROOT}/users/${httpoptions.username}`
  328. httpoptions.method = 'GET'
  329. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  330. }
  331. }
  332. return GITEA
  333. })();
  334. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  335. const GIT = (function(){
  336. function GIT(){}
  337. Object.assign(GIT, {
  338. 'switch user'(username){
  339. var httpoptions = new URL(selectedinstance.reposerver);
  340. httpoptions.username = selectedinstance.username
  341. httpoptions.password = selectedinstance.password
  342. return GITEA.user.getuser(httpoptions).then(()=>{
  343. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  344. {
  345. inherit: true, shell: true,
  346. env: ENV
  347. , cwd: instanceroot + '/' + repo
  348. , runas: processedArgs.runas
  349. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  350. })
  351. }
  352. )
  353. .catch(e => {
  354. console.error(e + 'Could not switch. Probably no such user.')
  355. })
  356. }
  357. })
  358. return GIT
  359. })();
  360. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  361. (function () {
  362. "use strict";
  363. if (!Array.prototype.earlyreduce) {
  364. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  365. var iterable = this;
  366. var donecallback = donecallback || (a=>a)
  367. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  368. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  369. // function *earlyReduceGenerator(acc, v, i, a) {
  370. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  371. var element = iterable[i]
  372. result = eachcallback(result, element, i, iterable)
  373. if(result.done) return donecallback(result)
  374. }
  375. // }
  376. return donecallback(result)
  377. }
  378. }
  379. }());
  380. // SAM : TODO Use nodeshellexec where to detect git installation dir
  381. var gitbash = shell_verse.getbash()
  382. var gitRepos = null
  383. var callshelltask = (args) => {
  384. // console.dir(args)
  385. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  386. return args;
  387. }
  388. return getshelltask(args)()
  389. }
  390. var runconfig = null;
  391. // PB : TODO -- rename as shelltask and bashtask['gitbash']... ( gitbash is a different bash... so previously named to specify that the bash distribution from git is the bash being used...)
  392. var getShellTask = (command, args, options) => {
  393. options = options || {}
  394. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  395. return () => {
  396. var p = callshell( [command, args, Object.assign({
  397. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  398. }, options)
  399. ])()
  400. if (options.ignorefailures) {
  401. return p.catch(e => {
  402. // Ignore. Not a major error.
  403. })
  404. }
  405. else return p;
  406. }
  407. }
  408. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  409. var getgitbashtask = (args, onEachError) => { return () => {
  410. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  411. }
  412. var getshelltask = (args) => {
  413. return args[0] === 'rm' ? getgitbashtask(args) : () => {
  414. return nodeShellExec.apply(null, args).catch(function(e){
  415. e.benign = args[2].benign;
  416. if(!e.benign) { console.error( JSON.stringify(e) ); }
  417. throw e
  418. })
  419. }
  420. }
  421. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  422. // -- Currently workaround in windows is to always run from a non-elevated shell.
  423. shell_verse.acquireElevationState().then((isElevated) => {
  424. // PB : TODO -- Implement queues using streams. Specially form bundling all elevated tasks as a single out of proc run with post elevated queue run postponed until the elevated stream and its dependencies are completed....
  425. const { existsSync } = require('fs');
  426. const existslink = function(name, cb){
  427. fs.lstat(name, (error, stats) => {
  428. if (error) {
  429. console.log(error);
  430. cb(error)
  431. }
  432. else {
  433. console.log("Stats object for: example_directory.txt");
  434. console.log(util.inspect(stats));
  435. // Using methods of the Stats object
  436. console.log("Path is file:", stats.isFile());
  437. console.log("Path is directory:", stats.isDirectory());
  438. cb(null, true)
  439. }
  440. });
  441. }
  442. const existsFolderSync = existsSync;
  443. var hasElxr = function(path, options, cb) {
  444. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  445. options = options || {};
  446. var tasks = [
  447. '/elxr' // Is there a subfolder named elxr
  448. , '/elxr/.git' // which is also a git repository
  449. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  450. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  451. ]
  452. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  453. var value = existsFolderSync(path + tpath);
  454. return { value, done : acc && !value };
  455. }).value }
  456. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  457. var value = existsFolderSync(path + tpath);
  458. return { value, done : acc && !value };
  459. }).value );
  460. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  461. var value = existsFolderSync(path + tpath);
  462. return { value, done : acc && !value };
  463. }).value);
  464. }
  465. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  466. var uselauncdirasdefaultroot = false;
  467. if( ENV.NODE_ENV === 'production') uselauncdirasdefaultroot = true;
  468. // PB : TODO -- enable for for production.
  469. 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
  470. var root = undefined // process.cwd() // Root need not be the launchdir...
  471. // we typicall assume the cwd to be the root. However this should default to
  472. // elxr parent if the root is not recongnizable as an instance root....
  473. // wd is our own environment variable probably corresponding to the root but need not be the same.
  474. // console.log(processedArgs.root)
  475. // console.log('PWD :' + ENV.PWD)
  476. // console.log('cwd : ' + process.cwd())
  477. // console.log('launchscriptdir : ' + path.normalize(__dirname))
  478. console.log('----------------------------------------------------------------')
  479. console.log('BEFORE DISCOVERY')
  480. console.log('version : ' + shell_verse.getVersion());
  481. console.log('process.env.wd : ' + process.env.wd)
  482. console.log('processedArgs.root : ' + processedArgs.root)
  483. console.log('----------------------------------------------------------------')
  484. console.log('wd :' + ENV.wd)
  485. console.log('PWD :' + ENV.PWD)
  486. console.log('cwd : ' + process.cwd())
  487. console.log(`thisscriptdir = ${thisscriptdir}`)
  488. console.log(`root = ${root}`)
  489. console.log(`instanceroot = ${instanceroot}`)
  490. console.log('----------------------------------------------------------------')
  491. if(!processedArgs.root){ // There is no runtime invoke time named args override.
  492. console.log('discovery')
  493. // Script may exists in the same location where we were launched(PWD) but that doesn't mean we r running from elxr.
  494. // script could have been copied tosome random location and run from there.
  495. // check elxr is preinstalled in same location. If so we need to chdir to parent. Else promt for confirmation of root.
  496. var launchdir = /*process.env.PWD ||*/ process.cwd() // mingw + node --inspect-brk behaves differently has a PWD that windows commands cannot recognize /d instead of D:\ and process.chdir fails..
  497. var parentdir = path.dirname( launchdir )
  498. var parentFolderHasElxr = hasElxrSync(parentdir)
  499. var launchFolderHasElxr = hasElxrSync(launchdir)
  500. if( path.normalize(launchdir + '/elxr') === thisscriptdir ) {
  501. // launchFolderHasElxr is false -- and yet thiscriptdir is still proper.
  502. if(!launchFolderHasElxr) {
  503. console.warn('Warning : detected thisscriptdir as subfolder but did not recognize launchdir as a proper root. elxr may not autoupdate...')
  504. // hasElxr checks for git repo status and elxr id stamping etc.
  505. // exlr tool may have been acquired unconventionally and we may not be able to manage it.
  506. // We will run anyway though
  507. }
  508. root = ENV.wd = launchdir;
  509. }
  510. else if( path.normalize(parentdir + '/elxr') === thisscriptdir ) {
  511. if(!parentFolderHasElxr) {
  512. console.warn('Warning : detected thisscriptdir as subfolder but did not recognize parentdir as a proper root. elxr may not autoupdate...')
  513. }
  514. // PB : TODO -- Cleanup this should no longer be needed... selectedinstance is properly initialized...
  515. root = ENV.wd = parentdir; // Default to the parent.
  516. }
  517. else {
  518. if (launchdir === thisscriptdir) {
  519. // Same directory doesn't mean we are being run from elxr sub directory. It could be a dislocated standalone elxr script.
  520. // PB : TODO -- In case elxr is not full elxr we need to locate it and relaunch to switch to the full version...
  521. // if(!parentFolderHasElxr) console.error('Invalid run location in subfolder that looks like elxr. We should probably abort.')
  522. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  523. // Confirmed we were run from an Unbuilt ( meaning non standalone ) elxr therefore we are in the elxr sub directory.
  524. root = ENV.wd = parentdir; // Default to the parent.
  525. // instanceroot = root = path.normalize(selectedinstance.root + '/..');
  526. // instanceoptions.splice( 0, 0, detected = { root });
  527. // instanceoptions.splice( 0, 0, detectfromroot(root));
  528. }
  529. else if(!parentFolderHasElxr) {
  530. // Either case we use the launchdir.
  531. // if(launchFolderHasElxr) {
  532. // // Probably a standalone run. Lets just go with it
  533. // root = ENV.wd = launchdir;
  534. // }
  535. // In standalone build script we may or not be in the same location.
  536. // We could have been run from the elxr subfolder. However we cant say for sure.
  537. // Most likely that the built version isn't the full elxr. We assume elxr doesnt exist and create an new elxr under..
  538. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  539. root = ENV.wd = launchdir;
  540. }
  541. else {
  542. // Built version was run from the full elxr subfolder
  543. root = ENV.wd = parentdir; // Default to the parent.
  544. // instanceoptions.splice( 0, 0, detected = { root })
  545. // instanceoptions.splice( 0, 0, detectfromroot(root))
  546. // Assume current selectedinstance.root is a new instance and create.
  547. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  548. // if(clioverrides.instanceName) {
  549. // if(clioverrides.node_env) {
  550. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  551. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  552. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  553. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  554. // // eg : floder name can be elixir01 but instance name is elixr
  555. // }
  556. // else {
  557. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + 'development')
  558. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  559. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  560. // }
  561. // }
  562. // else {
  563. // instanceroot = root = selectedinstance.root;
  564. // if(clioverrides.node_env) {
  565. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  566. // instanceoptions.splice( 0, 0, detectfromroot(root))
  567. // }
  568. // else {
  569. // // Nothing was specified... We only have one option from root.
  570. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  571. // }
  572. // }
  573. }
  574. }
  575. else if(launchFolderHasElxr) {
  576. root = ENV.wd = launchdir;
  577. // instanceoptions.splice( 0, 0, detected = { root })
  578. // instanceoptions.splice( 0, 0, detectfromroot(root))
  579. }
  580. else {
  581. // Ambiguous but assume script is standalone in the instanceroot
  582. // Lets defualt to the script parent assuming there is an instanceroot there. Hoever this should probably be a prompt where possible.
  583. // when we r in that mode.
  584. if(uselauncdirasdefaultroot) {
  585. // must be a new install in the selectedinstance.root with script invoked from some random location.
  586. if(!process.env.wd){
  587. // Working directory as a .env variable was not passed in.
  588. root = ENV.wd = launchdir;
  589. }
  590. else root = ENV.wd = process.env.wd
  591. }
  592. else {
  593. var scriptparent = path.dirname( thisscriptdir )
  594. root = ENV.wd = scriptparent;
  595. }
  596. }
  597. }
  598. }
  599. else {
  600. if(process.env.wd && process.env.wd !== processedArgs.root) throw 'wd and root must match.'
  601. root = ENV.wd = process.env.wd = processedArgs.root
  602. }
  603. var instanceroot = root
  604. ENV.PWD = ENV.wd
  605. ENV.NODE_ENV = processedArgs.node_env || (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  606. console.log('----------------------------------------------------------------')
  607. console.log('AFTER DISCOVERY')
  608. console.log('version : ' + shell_verse.getVersion());
  609. console.log('process.env.wd : ' + process.env.wd)
  610. console.log('processedArgs.root : ' + processedArgs.root)
  611. console.log('----------------------------------------------------------------')
  612. console.log('wd :' + ENV.wd)
  613. // process.chdir(ENV.wd) // Ensure cwd is the actual working dir.
  614. console.log('PWD :' + ENV.PWD)
  615. console.log('cwd : ' + process.cwd())
  616. console.log(`thisscriptdir = ${thisscriptdir}`)
  617. console.log(`root = ${root}`)
  618. console.log(`instanceroot = ${instanceroot}`)
  619. console.log('----------------------------------------------------------------')
  620. function ensureDirectoryExistence(filePath) { return shell_verse.ensureDirectoryExistence(filePath) }
  621. shell_verse.init({ statuslog, selectedinstance : { root : processedArgs.root
  622. , launchscript : __filename
  623. }, processedArgs, runtimestamp, ENV })
  624. // console.log('------------')
  625. // console.dir(shell_verse.selectedinstance.launchscript)
  626. // throw shell_verse.selectedinstance.launchscript
  627. // Instead of waiting for the root to be establised we start working at the current locatoin and then relocate when root changes.
  628. var runlogjson = `${root}/.elxr/run-${runtimestamp}/run.log`
  629. ensureDirectoryExistence(runlogjson)
  630. fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true})) // Initialize a new log file with "logrotate" for every run
  631. Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  632. // throw 'initbreak'
  633. // We no longer use this Folder name may be different from instanceName
  634. // var detectfromroot = function(root){
  635. // return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  636. // }
  637. // independent elxr cli operations
  638. var noprerequisites = {
  639. add : true, 'set-url' : true, 'repo-relocate' : true
  640. , remote : true, 'c' : true, 'h' : true
  641. , httpget : true, getuser : true
  642. , 'switch user' : true
  643. , 'switch' : true
  644. // , 'undefined' : true
  645. }
  646. var getowner = (args, selectedremote) => {
  647. selectedremote = selectedremote || {}
  648. return args.owner || selectedremote.owner || defaultowner
  649. }
  650. var __default = {
  651. // Common baseline repos for all chess chessinstances.
  652. repos : [
  653. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  654. , { repo : 'bbhverse' }
  655. , { repo : 'clientverse' }
  656. , { repo : 'serververse' }
  657. , { repo : 'elxr' }
  658. , { repo : 'ember-searchable-select' }
  659. , { repo : 'loopback-component-jsonapi' }
  660. , { repo : 'loopback-jsonapi-model-serializer' }
  661. , { repo : 'loopback-connector-mysql' }
  662. , { repo : 'loopback-connector-ds' }
  663. , { repo : 'ember-service-worker' }
  664. , { repo : 'ember-service-worker-asset-cache' }
  665. , { repo : 'ember-service-worker-cache-fallback' }
  666. , { repo : 'ember-service-worker-index' }
  667. , { repo : 'ember-sw-client-route' }
  668. , { repo : 'global-this' }
  669. ]
  670. // Requires elevation only in windows
  671. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  672. , exludeMergeRepos : { }
  673. }; // PB : TODO -- Use initialized instance instead of __default everywhere.
  674. var regexreplaceall = function(content, ps){
  675. var repmatches
  676. var replaced = content;
  677. while (repmatches = ps.strOrregexp.exec(content)) {
  678. if(content.length > 0) {
  679. var replacement = repmatches[0]
  680. for(var m = 1; m < repmatches.length; m++) {
  681. replacement = replacement.replace(repmatches[m], ps.substitutes[m-1])
  682. }
  683. replaced = replaced.replace( repmatches[0], replacement )
  684. }
  685. }
  686. return replaced
  687. }
  688. var cmds = {
  689. sqlpreprocess : {
  690. noprerequisites : true
  691. , cmdFn : function(args){
  692. // PB : TODO -- Load loopback app !!! for db connection to execute intermediate results for query genereation !!!
  693. return PATTERNAPI.includesql('', args._[1]).then(sqlquery => {
  694. // Do what we need to with the output
  695. // fs.writeFileSync(args._[1].replace('.sql', '.temp.g.sql'), sqlquery, { encoding: 'utf8'}) // For intermediate processing
  696. fs.writeFileSync(args._[1].replace('.i', ''), sqlquery + "\n" , { encoding: 'utf8'}) // Dynamic query output.
  697. // Static query debug output cannot be produced here... As EXEC sp_executesql must run to get the output. This can be produced by sqlfragmentexec in sql command mode.
  698. return sqlquery
  699. })
  700. // // PB : TODO -- move to dsql preprocesor
  701. // // var sqlquery = 'SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(args._[1])).replace(/\'/g,"''") + "'"
  702. // var sqlquery = fs.readFileSync(args._[1], { encoding: 'utf8'})
  703. // var regExp = /\-\-\s{{INCLUDE(.*?) ([\s\S]*?)}}\s\-\-/gm;
  704. // var options = {}
  705. // sqlquery = replacepatterns(sqlquery, regExp, (matches, sqlquery)=>{
  706. // if (matches[1] === 'ASDSQL') options.dsql = true
  707. // var replacement = {
  708. // distinctpatterntoreplace : new RegExp("\\-\\-\\s{{INCLUDE\\s" + matches[2] + "}}\\s\\-\\-","gm")
  709. // , detectedvaluepattern : matches[2]
  710. // // escaped dsql... //'SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(args._[1])).replace(/\'/g,"''") + "'"
  711. // }
  712. // if(options.dsql) replacement.substituedvalue = ('SET @dsql = @dsql + ' + "'" + ('' + fs.readFileSync(path.dirname(args._[1]) + '/' + matches[2])).replace(/\'/g,"''") + "'")
  713. // else replacement.substituedvalue = fs.readFileSync(path.dirname(args._[1]) + '/' + matches[2])
  714. // sqlquery = sqlquery.replace(replacement.distinctpatterntoreplace, replacement.substituedvalue);
  715. // regExp.lastIndex = 0;
  716. // })
  717. // // console.log(replaced)
  718. // fs.writeFileSync(args._[1] + '.d.sql', sqlquery, { encoding: 'utf8'})
  719. }
  720. , toArgs : function( o ){ return o }
  721. , interpret() { return { cmd : processedArgs._.slice(0, 1) } }
  722. }
  723. , remote : {
  724. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  725. , { cmd : processedArgs._.slice(0, 2).join(' '), runchoice : 'c' }) }
  726. , noprerequisites : true
  727. , independentcmd : true
  728. }
  729. , start : {
  730. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  731. , { cmd : 'start', runchoice : 'c'
  732. , node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV
  733. })}
  734. , toArgs : function( o ){
  735. return o
  736. }
  737. }
  738. , 'remote refresh' : {
  739. // return a interpreted set of arguments for this cmd run context.
  740. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  741. , { cmd : 'remote refresh', runchoice : 'c' }) }
  742. , noprerequisites : true
  743. , independentcmd : true
  744. // , requires : [ generateDependencies ]
  745. , toArgs : function( o ){
  746. return o
  747. }
  748. }
  749. , 'remote set-url' : {
  750. // return a interpreted set of arguments for this cmd run context.
  751. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  752. , { cmd : 'remote set-url', runchoice : 'c' }) }
  753. , noprerequisites : true
  754. , independentcmd : true
  755. // , requires : [ generateDependencies ]
  756. }
  757. , 'remote add' : {
  758. // return a interpreted set of arguments for this cmd run context.
  759. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  760. , { cmd : 'remote add', runchoice : 'c' }) }
  761. , noprerequisites : true
  762. , independentcmd : true
  763. // , requires : [ generateDependencies ]
  764. }
  765. , 'remote remove' : {
  766. // return a interpreted set of arguments for this cmd run context.
  767. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  768. , { cmd : 'remote remove', runchoice : 'c' }) }
  769. , noprerequisites : true
  770. , independentcmd : true
  771. }
  772. , 'addcollaborator' : {
  773. // Usage :
  774. // elxr addcollaborator instancename developer
  775. cmdFn : function(args){
  776. var __each = function(args){
  777. var collaborator = args.collaborator;
  778. if(!collaborator) {console.error('Error : collaborator required'); throw 'Error : collaborator required' }
  779. var repo = args.repo
  780. var repodef = selectedinstance.reposindexed[repo];
  781. var remotename = 'chess'
  782. if(!repodef) return
  783. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  784. var remotes = selectedinstance.reposerverinstances[selectedinstance.reposerver].remotes
  785. // console.log('-----------------------------------------------------')
  786. // console.log(repo)
  787. // // console.dir(remotes)
  788. // console.log('-----------------------------------------------------')
  789. // PB : TODO -- pick up remote definitions per repository...
  790. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  791. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  792. , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  793. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  794. ))
  795. if( !reposmanfiest.error ) {
  796. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  797. var reporemotes = utils.assign(remotes, reposmanfiest.reposerverinstances[selectedinstance.reposerver].remotes)
  798. }
  799. else {
  800. var reporemotenames = remotenames
  801. var reporemotes = remotes
  802. }
  803. var remote = reporemotes[remotename]
  804. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  805. // selectedinstance.reposerverinstances[reposerver]
  806. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  807. var httpoptions = new URL(reposerver);
  808. httpoptions = {
  809. hostname: httpoptions.hostname
  810. , protocol : httpoptions.protocol
  811. }
  812. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  813. // PB : TODO -- handle credentials properly. cant mix and match passwords..
  814. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  815. // console.log(___args)
  816. // PB : TODO -- Check valid collaborator before adding...
  817. return GITEA.repository.addcollaborator(httpoptions, repodef, remote.owner, collaborator).then( v => {
  818. if(v === true) {
  819. console.log('-----------------------------------------------------')
  820. console.log('addcollaborator successful for ' + repo + ' ' + collaborator)
  821. console.log('-----------------------------------------------------')
  822. }
  823. } )
  824. }
  825. var promises = []
  826. var repos = Object.keys(selectedinstance.reposindexed)
  827. repos.forEach(repo => { promises.push(__each({ repo, collaborator : args._[2]})) }) // PB : TODO -- Move to toArgs.
  828. return Promise.all(promises).then(pr => { console.log('addcollaborator done') })
  829. }
  830. }
  831. , 'isurlaccessible' : {
  832. noprerequisites : true
  833. , independentcmd : true
  834. , toArgs : function( o ){
  835. return { url : o._[1] }
  836. }
  837. }
  838. , resetgitconfig : {
  839. // return a interpreted set of arguments for this comd run context.
  840. // cmdFn : resetgitconfig,
  841. interpret() { return { cmd : 'resetgitconfig' } }
  842. , noprerequisites : true
  843. , independentcmd : true
  844. }
  845. , reinit : {
  846. // return a interpreted set of arguments for this comd run context.
  847. // cmdFn : reinit
  848. // ,
  849. interpret() { return { cmd : 'reinit' } }
  850. , noprerequisites : true
  851. , independentcmd : true
  852. , requiresElevation : true
  853. // , requires : [ generateDependencies ]
  854. }
  855. , init : {
  856. // return a interpreted set of arguments for this comd run context.
  857. // cmdFn : init
  858. // ,
  859. interpret() { return { cmd : 'init' } }
  860. , noprerequisites : true
  861. , independentcmd : true
  862. , requiresElevation : true
  863. // , requires : [ generateDependencies ]
  864. }
  865. , switch : {
  866. interpret() {
  867. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  868. , reposerver : __default.reposerver // .?.?.?
  869. }
  870. }
  871. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  872. }
  873. , 'switch user' : {
  874. interpret() {
  875. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  876. }
  877. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  878. }
  879. // Flat linear structure. Every subcommand should have a top level 'label'
  880. , 'users' : {
  881. // default to the users list
  882. subcommands : { list : {} }
  883. , cmdFn : ()=>getCredentials() // default
  884. , cmd : 'users'
  885. , noprerequisites : true
  886. }
  887. , 'users list' : {
  888. cmdFn : ()=>getCredentials()
  889. , cmd : 'users list'
  890. , noprerequisites : true
  891. }
  892. , 'get-upstream' :{
  893. // cmdFn : oplist['get-upstream'] // default
  894. // ,
  895. cmd : 'get-upstream'
  896. , noprerequisites : true
  897. , independentcmd : true
  898. , interpret() { return { cmd : 'get-upstream' } }
  899. }
  900. , 'g' : {
  901. cmd : 'g'
  902. , noprerequisites : true
  903. }
  904. , 'link' : {
  905. 'cmd' : 'link'
  906. // , cmdFn : function( sourecpath, filename, dir ){
  907. // var afterTargetPath = (dir)=>{
  908. // console.dir(dir);
  909. // // var tasks = [
  910. // // () => {
  911. // // // Use junctions to avoid npm package issues
  912. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  913. // // inherit: true, shell: true
  914. // // , cwd : dir || instanceroot
  915. // // , env: ENV
  916. // // }).catch((e) => { console.error(e) })
  917. // // return p;
  918. // // }
  919. // // ];
  920. // }
  921. // // console.dir(ENV)
  922. // if(!dir) getCurrentFolder().then(afterTargetPath);
  923. // else afterTargetPath(dir)
  924. // }
  925. , cmdFn : function( cmdopts ){
  926. // sourecpathandfile should include name of file name
  927. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  928. // console.log(processedArgs)
  929. if(!targetfilename) return Promise.reject('error no file provided for linking')
  930. targetdir = cmdopts.targetdir || ENV.wd
  931. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  932. var tasks = [
  933. () => {
  934. // Use junctions to avoid npm package issues
  935. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  936. inherit: true, shell: true
  937. , cwd : targetdir
  938. , env: ENV
  939. }).catch((e) => { console.error(e) })
  940. return p;
  941. }
  942. ];
  943. var etask = ()=>{
  944. return any(tasks).then(() => {
  945. fs.writeFileSync('run.done', 'success')
  946. }).catch(() => {
  947. fs.writeFileSync('run.done', 'error')
  948. })
  949. }
  950. etask.statuslog = statuslog
  951. etask.selectedinstance = selectedinstance
  952. etask.processedArgs = processedArgs
  953. etask.runtimestamp = runtimestamp
  954. etask.ENV = ENV
  955. return shell_verse.runElevated(etask)
  956. }
  957. , noprerequisites : true
  958. , privileged : true
  959. }
  960. , 'tshell' : {
  961. // Transparent Shell
  962. toArgs : function( o ){ return o }
  963. , cmdFn : function( cmdopts ){
  964. var tasks = [
  965. () => {
  966. return nodeShellExec(`"${gitbash}"`, ['-c', `"${processedArgs._.join(' ')}"` ]
  967. , {
  968. // cwd: args.repodir .... cwd is not needed here as the callee will already launch with
  969. // , stdio: ['pipe', process.stdout, process.stderr]
  970. // ,
  971. inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
  972. }
  973. ).catch(function(e){
  974. console.error( JSON.stringify(e) );
  975. throw e
  976. })
  977. }
  978. ];
  979. var etask = ()=>{
  980. return any(tasks).then(() => {
  981. fs.writeFileSync('run.done', 'success')
  982. }).catch(() => {
  983. fs.writeFileSync('run.done', 'error')
  984. })
  985. }
  986. etask.statuslog = statuslog
  987. etask.selectedinstance = { root : processedArgs.root }
  988. etask.processedArgs = processedArgs
  989. etask.runtimestamp = runtimestamp
  990. etask.ENV = ENV
  991. // sourecpathandfile should include name of file name
  992. if(cmdopts.runas) {
  993. return shell_verse.runElevated(etask)
  994. }
  995. else return shell_verse.runNonElevated(etask)
  996. }
  997. }
  998. }
  999. function interpret() {
  1000. var interpreted = this
  1001. // Non custom command has universal positiona args.
  1002. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  1003. interpreted.runchoice = interpreted.cmd ? 'c' : null
  1004. // interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  1005. // return clioverrides
  1006. // cmds[cmd] = {
  1007. // interpret() {
  1008. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  1009. // }
  1010. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  1011. // instanceName : true, instanceType : true, reposerver : true } }
  1012. // }
  1013. // ... PB : TODO -- use cmd.toArgs
  1014. // interpreted.cmd = this.cmd
  1015. return interpreted
  1016. }
  1017. var interpretrun = function(){
  1018. var cmd = processedArgs._[0];
  1019. var interpretations = {
  1020. 'git' : function transparentshell(){
  1021. // PB : TODO -- put some security here for unknown shell executions... Pre-qualify...
  1022. return { cmd : 'tshell', noprerequisites : true }
  1023. }
  1024. }
  1025. var tshell = interpretations[cmd];
  1026. if(tshell) return tshell();
  1027. return cmds[cmd] && cmds[cmd].interpret ? cmds[cmd].interpret() : (function(){
  1028. return cmds[cmd] = utils.assign(cmds[cmd] || {}, interpret.call({ cmd, toArgs : function( o ){
  1029. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  1030. return o } }))
  1031. })()
  1032. }
  1033. var chessinstances = { current_run : {} };
  1034. var clioverrides = interpretrun()
  1035. clioverrides = utils.assign( { cmd : processedArgs._[0], node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV }
  1036. , clioverrides, cmds[clioverrides.cmd].toArgs(processedArgs), { root : ENV.wd } )
  1037. function acquirelocalinstances(selected){
  1038. // utils.assign is used to cleanup duplicates... assuming it is probably not clean.
  1039. // PB : TODO -- if require fails decipher instanceName from findlocalinstances using the root...
  1040. try { var existinglocalinstances = require(path.normalize(selected.root + '/chessinstances.js'))}
  1041. catch(e){
  1042. console.warn( 'Local instances not found.' ) // This is not an error. A new fresh instance is probably being setup.
  1043. var existinglocalinstances = { current_run : {}, error : true }
  1044. }
  1045. chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, existinglocalinstances);
  1046. // console.dir(chessinstances)
  1047. return chessinstances
  1048. }
  1049. function findlocalinstances(chessinstances, instanceoptions){
  1050. // We can expect a .elxr at each level in folder and 2 levels up. higher up we will find a shared instance chessinstances.js
  1051. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../../' /* instanceNames */].
  1052. earlyreduce( ( reduced, p, i, a )=>{
  1053. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  1054. if(existsSync( localinstancesPath )) {
  1055. try {
  1056. acquirelocalinstances( { root : `${instanceroot}/${p}` } )
  1057. if(chessinstances.error) {
  1058. delete chessinstances.error; delete chessinstances.e
  1059. return {}
  1060. }
  1061. return Object.keys(chessinstances).earlyreduce( ( reduced, instanceName) => {
  1062. return Object.keys(chessinstances[instanceName]).earlyreduce( (reduced, instanceType) => {
  1063. // Scan to find a matching instanceroot
  1064. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  1065. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  1066. return {
  1067. value : chessinstances[instanceName][instanceType]
  1068. , done : true
  1069. };
  1070. }
  1071. })
  1072. })
  1073. }
  1074. catch(e){
  1075. return { }
  1076. }
  1077. }
  1078. else return { }
  1079. }
  1080. )
  1081. }
  1082. // PB : TODO -- Move this to utils assign... as an array merge option.
  1083. var mergeObjByKey = function(arrOfObjs, keyName) {
  1084. var keyedDistinct = {}
  1085. var distinctArrOfObjs = []
  1086. arrOfObjs.forEach( o => {
  1087. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1088. })
  1089. Object.keys(keyedDistinct).forEach(key => {
  1090. distinctArrOfObjs.push( utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1091. , ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1092. })
  1093. return distinctArrOfObjs;
  1094. }
  1095. var cacheWriteInstanceConfig = function(chessinstances, instanceroot, selectedinstance){
  1096. if(selectedinstance) {
  1097. var instanceName = selectedinstance.instanceName ;
  1098. var node_env = selectedinstance.node_env;
  1099. // PB : TODO -- handle current_run switch...
  1100. // console.dir(chessinstances)
  1101. // PB : TODO -- We should be able to do simply merge at a higher level using assign
  1102. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
  1103. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
  1104. }
  1105. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1106. }
  1107. var loadmanifest = function( mpath, moverrides ){
  1108. try {
  1109. // PB : TODO -- pick up remote definitions per repository...
  1110. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  1111. , {}, require(path.normalize( mpath + '/repo-manifest'))( {utils}, null, moverrides ))
  1112. }
  1113. catch(e){
  1114. // console.warn(e);
  1115. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }, { error : true, e }, moverrides)
  1116. }
  1117. }
  1118. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  1119. if(clioverrides.reconfirm) {
  1120. var reconfirm = getReconfirmAll()
  1121. }
  1122. else { var reconfirm = {}; }
  1123. var shouldPrompt = function(k, possiblePrompts, target){
  1124. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  1125. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  1126. || reconfirm[k])
  1127. }
  1128. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  1129. return {
  1130. get (){
  1131. return any( promptable.dependencies || [] ).then(()=>{
  1132. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  1133. var asyncprop = Promise.resolve(propValue)
  1134. if(promptable.interpret){
  1135. asyncprop = promptable.interpret(propValue)
  1136. }
  1137. return asyncprop.then(
  1138. ()=>{
  1139. Object.defineProperty(this, propName, {
  1140. value: propValue,
  1141. writable: true,
  1142. configurable : true,
  1143. enumerable : true
  1144. });
  1145. return propValue
  1146. }
  1147. )
  1148. })
  1149. } )
  1150. }
  1151. // , set (propValue){
  1152. // Object.defineProperty(this, propName, {
  1153. // value: propValue,
  1154. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  1155. // configurable : true,
  1156. // enumerable : true
  1157. // })
  1158. // return propValue;
  1159. // }
  1160. , configurable : true
  1161. , enumerable : true
  1162. }
  1163. }
  1164. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  1165. return function(prompts, k, i, a){
  1166. // Reducer for all prompts on targets.
  1167. // No local instances config found. We use a default initialized instance available in selectedinstance
  1168. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  1169. // PB : TODO -- selectedinstance === __default check to prompt everything...
  1170. if( shouldPrompt(k, possiblePrompts, target) ) {
  1171. delete reconfirm[k];
  1172. // console.log(k)
  1173. // console.dir(possiblePrompts); //console.dir(target)
  1174. prompts.push(async ()=>{
  1175. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  1176. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  1177. // var asyncthis = Object.assign(this);
  1178. // By default Latest altered state is provided which is an implicit reference directly.
  1179. console.log('----------------------------------------------------')
  1180. console.log(k)
  1181. console.dir(choices[k])
  1182. if(!promptables[k]) promptables[k] = {}
  1183. promptables[k].choices = choices[k]
  1184. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  1185. return await target[k]
  1186. })
  1187. }
  1188. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  1189. return prompts
  1190. }
  1191. }
  1192. // PB : TODO -- Use queueing with async tasks..
  1193. var performPullOrClone = (repodef, branch, owner, errHandler, elevatedBatch, regularBatch) => {
  1194. var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
  1195. var pT = getPullOrCloneTask(repodef, branch, owner, errHandler, elevatedBatch, regularBatch)
  1196. // var waitForBatchAdditions = function(){
  1197. // return pT;
  1198. // }
  1199. // Execute is implied.
  1200. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  1201. // else
  1202. return pT() // Execute it.
  1203. }
  1204. var elevatedRunasRepos = null
  1205. var exludeMergeRepos = [];
  1206. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1207. var checkoutMap = { 'development': 'master' }
  1208. var oplist = {
  1209. 'h': () => { console.log(elxr.help()); return '-h' }
  1210. , 'clean' : () => {
  1211. // delete all node_module folders and links.
  1212. var tasklist = [];
  1213. dirs( (dir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + dir.name })()), instanceroot )
  1214. return Promise.all(tasklist)
  1215. }
  1216. // , 'undefined': () => { return acquireChoices( {} ); }
  1217. , 'isurlaccessible' : function(args){
  1218. // args.url... .. PB : TODO -- Extract from url
  1219. args = args || {}
  1220. var u = new URL(args.url || selectedinstance.reposerver)
  1221. console.log(u)
  1222. var httpoptions = { hostname : u.host || 'git.bbh.org.in', protocol : u.protocol || 'https'
  1223. , method : 'GET'
  1224. , username : args.username || selectedinstance.username || 'chess'
  1225. , password : selectedinstance.password || 'chess'
  1226. }
  1227. httpoptions.path = args.path || `/`
  1228. return new Promise(function( resolve, reject ){
  1229. RESTAPI.get(httpoptions, function(){
  1230. console.log('URL is accessible')
  1231. resolve(true)
  1232. }, function(){
  1233. console.error('URL is not accessible')
  1234. resolve(false)
  1235. })
  1236. })
  1237. }
  1238. , 'reset': () => {
  1239. // Reset NPM packages semver so major versions can be updated.
  1240. const fs = require('fs')
  1241. const wipeDependencies = (__package) => {
  1242. const file = fs.readFileSync(__package + '/package.json')
  1243. const content = JSON.parse(file)
  1244. for (var devDep in content.devDependencies) {
  1245. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1246. content.devDependencies[devDep] = '*';
  1247. }
  1248. }
  1249. for (var dep in content.dependencies) {
  1250. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1251. content.dependencies[dep] = '*';
  1252. }
  1253. }
  1254. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  1255. }
  1256. var repos = ['client'];
  1257. // repos = gitRepos;
  1258. repos.forEach(wipeDependencies)
  1259. // if (require.main === module) {
  1260. // } else {
  1261. // module.exports = wipeDependencies
  1262. // }
  1263. }
  1264. , 'upgrade': () => {
  1265. console.log('upgrade.......')
  1266. var tasks = [
  1267. () => {
  1268. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  1269. inherit: true, shell: true
  1270. , env: ENV
  1271. }).catch((e) => { console.error(e) })
  1272. p.position = 1;
  1273. console.log('One')
  1274. return p;
  1275. }
  1276. , () => {
  1277. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  1278. inherit: true, shell: true
  1279. , env: ENV
  1280. }).catch((e) => { console.error(e) })
  1281. p.position = 2;
  1282. console.log('Two')
  1283. return p;
  1284. }
  1285. , () => {
  1286. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  1287. inherit: true, shell: true
  1288. , env: ENV
  1289. }).catch((e) => { console.error(e) })
  1290. p.position = 3;
  1291. console.log('Three')
  1292. return p;
  1293. }
  1294. , () => {
  1295. var p = nodeShellExec('n', ['latest'], {
  1296. inherit: true, shell: true
  1297. , env: ENV
  1298. }).catch((e) => { console.error(e) })
  1299. p.position = 4;
  1300. console.log('Four')
  1301. return p;
  1302. }
  1303. ]
  1304. any(tasks)
  1305. console.log('.......done')
  1306. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  1307. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  1308. console.info('Uninstalling existing ember globally');
  1309. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  1310. stdio: ['pipe', process.stdout, process.stderr],
  1311. inherit: true,
  1312. shell: true,
  1313. cwd: path.dirname(__dirname),
  1314. env: ENV
  1315. })
  1316. step1.on('close', () => {
  1317. console.info('Installing ember globally');
  1318. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  1319. stdio: ['pipe', process.stdout, process.stderr],
  1320. inherit: true,
  1321. shell: true,
  1322. cwd: path.dirname(__dirname),
  1323. env: ENV
  1324. })
  1325. step2.on('close', () => {
  1326. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  1327. stdio: ['pipe', process.stdout, process.stderr],
  1328. inherit: true,
  1329. shell: true,
  1330. cwd: path.dirname(__dirname),
  1331. env: ENV
  1332. })
  1333. })
  1334. })
  1335. }
  1336. , 'push': () => {
  1337. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  1338. // init remote bare from local
  1339. // pushandinitremotebare
  1340. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  1341. // connect to repo server -- net use 172.16.0.27
  1342. // cd 172.16.0.27/repos/
  1343. // mkdir repo.git
  1344. // cd repo.git
  1345. // git init --bare
  1346. // cd localrepo
  1347. // git remote rename origin githubclone
  1348. // git remote add origin //172.16.0.27/repos/repo.git
  1349. // git push origin master
  1350. var repo = processedArgs._[1];
  1351. var remote = 'origin'
  1352. var sequentialTaskShellCommands = [];
  1353. if (!existsSync(`Z:/${repo}.git`)) {
  1354. sequentialTaskShellCommands = [
  1355. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  1356. // inherit : true, shell: true
  1357. // , env: ENV
  1358. // }]
  1359. ['pwd', { cwd: 'Z:', inherit: true }]
  1360. , ['mkdir', [`${repo}.git`], {
  1361. cwd: `Z:`
  1362. , inherit: true, shell: true
  1363. , env: ENV
  1364. }]
  1365. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  1366. , ['git', ['init', '--bare'], {
  1367. cwd: `Z:/${repo}.git`
  1368. , inherit: true, shell: true
  1369. , env: ENV
  1370. }]
  1371. // PB : TODO -- Do this conditionally only...
  1372. , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  1373. console.log(`Ignoring ${remote} rename error : ` + err); return true; //return true to continue.
  1374. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  1375. , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  1376. // PB : TODO -- If threre is a gitbubclone origin
  1377. // Set the master to pull from the local repo.
  1378. ]
  1379. if (!existsSync(`Z:`)) {
  1380. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  1381. inherit: true, shell: true
  1382. , env: ENV
  1383. }])
  1384. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  1385. // throw 'done'
  1386. }
  1387. }
  1388. sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  1389. // console.dir(sequentialTaskShellCommands);
  1390. var tasks = [];
  1391. sequentialTaskShellCommands.forEach(shellcmd => {
  1392. // console.log(shellcmd)
  1393. tasks.push(() => {
  1394. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  1395. return p;
  1396. })
  1397. })
  1398. any(tasks);
  1399. }
  1400. , 'is-git-repo': (dir) => {
  1401. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  1402. }
  1403. // git remote equivalents...
  1404. // git branch --set-upstream-to=elixir-unc/master master
  1405. // git push --set-upstream elixir-unc branch..
  1406. , 'remote': (args) => {
  1407. // Subcommands!
  1408. // PB : TODO -- we can now pass in hypehnated args...
  1409. if(!processedArgs.v) return false; // Only -v is supported presently..
  1410. var serial_perform = (repo) => {
  1411. var options = { cwd: instanceroot + '/' + repo }
  1412. return [
  1413. ['git', ['remote', '-v'], options]
  1414. ]
  1415. }
  1416. var x = (args) => {
  1417. var tasq = () => {
  1418. // console.log(args)
  1419. return nodeShellExec.apply(null, args).catch(e => {
  1420. // We continue on failure.
  1421. console.error(tasq.toString())
  1422. })
  1423. }
  1424. tasq.toString = function(){
  1425. return JSON.stringify(args)
  1426. }
  1427. return tasq;
  1428. }
  1429. var perform = (dir) => {
  1430. return any(serial_perform(dir.name).map(x))
  1431. }
  1432. dirs(perform)
  1433. }
  1434. , 'remote set-url': (args) => {
  1435. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  1436. var __args = {
  1437. remotename : args.remotename || processedArgs._[2]
  1438. , url : args.url || processedArgs._[3]
  1439. , branch : args.branch || processedArgs._[4] || 'master'
  1440. }
  1441. __args.upstream = args['upstream'] || processedArgs._[5] || `${__args.remotename}/${__args.branch}`
  1442. // pushable doesn't mean the remote doesn't support being pushed to.
  1443. // 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.
  1444. // PB : TODO -- change this to enablepushing.
  1445. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  1446. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1447. var remotename = __args.remotename
  1448. var url = __args.url
  1449. var branch = __args.branch
  1450. var upstream = __args.upstream
  1451. console.log('remotename : ' + args.remotename)
  1452. var serial_perform_git_seturl = (reponame) => {
  1453. var options = { cwd: instanceroot + '/' + reponame }
  1454. // console.log(reponame)
  1455. var serialcmds = [
  1456. ['git', ['remote', 'set-url', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1457. ]
  1458. if (!pushable) {
  1459. serialcmds.push(['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }])
  1460. }
  1461. var requiresElevation = selectedinstance.elevated.find( r => r.repo === reponame)
  1462. serialcmds.push(['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame, requiresElevation }]) // requires elevation based on repo
  1463. serialcmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1464. return serialcmds
  1465. }
  1466. var x = (xargs) => {
  1467. var tasq = () => {
  1468. // console.log(args)
  1469. var task = (onsuccess, onerror)=>{
  1470. return ()=>{
  1471. return nodeShellExec.apply(null, xargs).then( onsuccess ).catch(e => {
  1472. // We continue on failure.
  1473. // No such remote
  1474. if(e.messages[0].search('No such remote') > -1 ){
  1475. console.log(remotename + ' Remote doesnt exist will add.')
  1476. return oplist['remote add']( args )
  1477. }
  1478. console.error(util.inspect(e) + ' ' + tasq.toString())
  1479. })
  1480. }
  1481. }
  1482. if(xargs[2].requiresElevation){
  1483. if(!isElevated) {
  1484. var etask = task( ()=>{ return remotename } )
  1485. etask.statuslog = statuslog
  1486. etask.selectedinstance = selectedinstance
  1487. etask.processedArgs = processedArgs
  1488. etask.runtimestamp = runtimestamp
  1489. etask.ENV = ENV
  1490. return shell_verse.runElevated(etask)
  1491. }
  1492. }
  1493. return task(
  1494. () => { fs.writeFileSync('run.done', 'success')}
  1495. , () => { fs.writeFileSync('run.done', 'error') }
  1496. )()
  1497. }
  1498. tasq.toString = function(){ return JSON.stringify(args) }
  1499. return tasq;
  1500. }
  1501. var perform_git_seturl = (dir) => {
  1502. return oplist['is-git-repo'](dir).then((logEntry) => {
  1503. return any(serial_perform_git_seturl(dir.name).map(x))
  1504. }).catch((e) => {
  1505. console.log(e + ' Failed not recognized as a git repo : ' + dir.name)
  1506. })
  1507. }
  1508. if(args.dir) return perform_git_seturl(args.dir) // do this for a specific repo
  1509. else return dirs(perform_git_seturl) // Do for all
  1510. }
  1511. // , 'reset' : ()=>{
  1512. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  1513. // // Reset the whole installation pertaining to this elxr folder.
  1514. // }
  1515. , 'remote exists': (args) => {
  1516. var __args = {
  1517. remotename : args.remotename|| processedArgs._[2]
  1518. , url : args.url || processedArgs._[3]
  1519. , branch : args.branch || processedArgs._[4]
  1520. }
  1521. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  1522. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  1523. var commands = [
  1524. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  1525. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  1526. [
  1527. // 'git', ['remote', '-v']
  1528. 'git', ['config', `remote.${__args.remotename}.url`]
  1529. , utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1530. , {
  1531. benign : args.benign, ignorefailures : args.ignorefailures,
  1532. evaluateResult : function(err, result){
  1533. return [
  1534. +result.code === 0
  1535. , result
  1536. ]
  1537. }
  1538. } , options) ]
  1539. ]
  1540. var mapped = commands.map(getshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  1541. mapped.push( function(prevserialtaskresult) {
  1542. var pt = [false , null]
  1543. if(prevserialtaskresult.error) {
  1544. // Previous task has failed.
  1545. pt[1] = prevserialtaskresult.error[1]
  1546. }
  1547. else pt = prevserialtaskresult;
  1548. console.dir(prevserialtaskresult)
  1549. return getshelltask(['git', ['ls-remote', `${__args.url}`], utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1550. , {
  1551. benign : args.benign, ignorefailures : args.ignorefailures,
  1552. evaluateResult : function(err, result){
  1553. if(+result.code !== 0) return [pt, [ false, result]]
  1554. // var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  1555. return [pt, [true, result] ]
  1556. }
  1557. } , options) ])().catch( e => {
  1558. console.error(e)
  1559. return [pt, [ false, null]]
  1560. })
  1561. })
  1562. return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
  1563. console.dir(allresolved)
  1564. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  1565. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  1566. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  1567. : console.log('was not added as a remote but url is currently accessible.')
  1568. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  1569. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  1570. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  1571. : [0, 1] // => was not added and remote and url is accessible.
  1572. }).catch(e => {
  1573. console.log(e)
  1574. return [0, 0]
  1575. })
  1576. }
  1577. , 'remote refresh' : (args) => {
  1578. var url = args._[2] || selectedinstance.reposerver
  1579. return oplist['isurlaccessible']({ url }).then(( baccess )=>{
  1580. if(!baccess) {
  1581. var reposerver = selectedinstance.reposerverinstances[url]
  1582. if(!reposerver.external) {
  1583. // Internal server not accessible ask to switch to external.
  1584. console.log('Internal server not accsssible. Will switch to external')
  1585. // console.dir(selectedinstance.reposerverinstances)
  1586. url = reposerver.externalreposervers[0]
  1587. }
  1588. else {
  1589. console.log('External server not accsssible. Will switch to interal')
  1590. // PB : TODO -- Prompt and then switch.
  1591. url = reposerver.internalreposervers[0]
  1592. }
  1593. return oplist['isurlaccessible']({ url }).then(( baccess )=>{
  1594. if(!baccess) {
  1595. console.log('Neither internal nor external servers are accessible.... Presenting choices...')
  1596. console.log('PB : TODO -- Present appropriate choices...')
  1597. // Redo whole command...
  1598. }
  1599. return dorefresh()
  1600. })
  1601. }
  1602. dorefresh()
  1603. console.log(baccess)
  1604. }).catch((err)=>{ console.error(err) })
  1605. function dorefresh(){
  1606. // if(args.url === selectedinstance.reposerver) {
  1607. // // No change. Just refresh with same url anyway. We do not know which of the repos is not up to date and is an outlier.
  1608. // }
  1609. // else {
  1610. // // Also refreshs anyway
  1611. // }
  1612. args = args || {}
  1613. var __args = {
  1614. url : args.url || processedArgs._[2] || selectedinstance.reposerver
  1615. // , branch : args.branch || processedArgs._[4]
  1616. }
  1617. var serial_perform = (repo) => {
  1618. // if(repo === 'setup' || repo === 'chess-server-lib'){
  1619. var options = { cwd: instanceroot + '/' + repo }
  1620. console.log('serial_perform : ' + repo)
  1621. return [
  1622. ['git', ['remote', '-v'], options]
  1623. ]
  1624. // }
  1625. // else return []
  1626. }
  1627. var x = (args) => {
  1628. // console.log('MapX was called')
  1629. var tasq = () => {
  1630. console.log('--------------------------')
  1631. console.log(args)
  1632. return nodeShellExec.apply(null, args).catch(e => {
  1633. console.log('caught error ------------------------' + JSON.stringify(e))
  1634. // We continue on failure.
  1635. console.error(tasq.toString() + args[2].cwd)
  1636. })
  1637. }
  1638. tasq.toString = function(){
  1639. // console.log('sadfasdf------------------------')
  1640. return JSON.stringify(args) // PB : TODO -- Is this needed ?
  1641. }
  1642. return tasq;
  1643. }
  1644. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  1645. var remotes = selectedinstance.reposerverinstances[__args.url].remotes
  1646. // use the repo manifest to create missing remotes.
  1647. function perform_remote_refresh(dir){
  1648. var repo = dir.name
  1649. var ___args = {url : __args.url, repo}
  1650. if(repo === '.elxr') return Promise.resolve(true)
  1651. if(repo === '.git') return Promise.resolve(true)
  1652. if(repo === 'Downloads') return Promise.resolve(true)
  1653. // PB : TODO -- pick up remote definitions per repository...
  1654. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  1655. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  1656. , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  1657. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  1658. ))
  1659. if( !reposmanfiest.error ) {
  1660. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  1661. var reporemotes = utils.assign([], remotes, reposmanfiest.reposerverinstances[___args.url].remotes)
  1662. }
  1663. else {
  1664. var reporemotenames = remotenames
  1665. var reporemotes = remotes
  1666. }
  1667. return (()=>{
  1668. var promises = []
  1669. return any(serial_perform(repo).map(x)).then(()=>{
  1670. var branch = args.branch || 'master' // PB : TODO -- Dont default branch here.. Let each repos current state define this... ???
  1671. reporemotenames.forEach(rm =>{
  1672. console.log('Processing : ' + rm + ' ' + dir.name)
  1673. // if(repo != 'elxr') return //test
  1674. // if(repo != 'elixir-config-development') return //test
  1675. // if(repo != 'elixir-server') return //test
  1676. promises.push( ((rm) => {
  1677. var remotename = rm
  1678. var repodef = selectedinstance.reposindexed[repo];
  1679. if(!repodef) return
  1680. // if( repo !== 'cihsr-data') return
  1681. // username and owner are two different things. The repository (possibly forked) under the username is when the {{owner}} portion of the repo path is the same as the user.
  1682. // When one user or organiztion shares repos with others through a team without a fork a different user has access to a different {{owner}} path repo.
  1683. var remote = reporemotes[remotename]
  1684. // console.log(repodef)
  1685. // console.log(remote)
  1686. var owner = getowner(repodef, remote)
  1687. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  1688. // selectedinstance.reposerverinstances[reposerver]
  1689. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  1690. var httpoptions = new URL(reposerver);
  1691. httpoptions = {
  1692. hostname: httpoptions.hostname
  1693. , method: 'GET'
  1694. , protocol : httpoptions.protocol
  1695. }
  1696. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  1697. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  1698. // console.log(___args)
  1699. var repourl = reporemotes[remotename].url + '/' + repo
  1700. // PB : TOOD -- USE GITTEA API
  1701. // oplist['isurlaccessible']({ url : repourl }).then((baccess)=>{
  1702. return GITEA.repository.exists( httpoptions, repo, owner ).then((bexists)=>{
  1703. console.log(remotename + ' ' + repourl)
  1704. if(bexists) {
  1705. console.log(remotename + ' ' + repourl + ' is accessible')
  1706. return ((remotename)=>{
  1707. return oplist['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1708. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1709. })(remotename)
  1710. // get upstream remote choice from user !!!
  1711. // PB : TODO -- Set upstream , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  1712. }
  1713. }).catch(e => {
  1714. console.warn(remotename + ' ' + repourl + ' ' + e) // Skip nonexistant not necessarily quietly
  1715. })
  1716. })(rm)
  1717. )
  1718. })
  1719. return Promise.all(promises).then( accessibleremotes => {
  1720. while(!accessibleremotes[accessibleremotes.length -1] && accessibleremotes.length) accessibleremotes.splice(accessibleremotes.length -1, 1)
  1721. if(accessibleremotes.length) {
  1722. ((remotename)=>{
  1723. var upstream = `${remotename}/${branch}`
  1724. var remote = reporemotes[remotename]
  1725. return oplist['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1726. , upstream
  1727. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1728. })( accessibleremotes[accessibleremotes.length -1] )
  1729. }
  1730. }).catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  1731. })
  1732. })()
  1733. }
  1734. if(isElevated) {
  1735. var elevatedpromises = []
  1736. selectedinstance.elevated.forEach( r => { elevatedpromises.push(perform_remote_refresh({ name : r.repo })) } )
  1737. return Promise.all(elevatedpromises)
  1738. }
  1739. else return dirs(perform_remote_refresh)
  1740. }
  1741. }
  1742. , 'remote add': (args) => {
  1743. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  1744. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  1745. // That explicitly has a remote name prefix.
  1746. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  1747. // git branch branch_name -u your_new_remote/branch_name -- older versions
  1748. // git branch -vv -- Detect which branch are we tracking.
  1749. // default upstream should be users own fork.
  1750. // Also need alias branches to
  1751. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  1752. // probably git merge from all remotes... and relevant branches...
  1753. // alias pushall='for i in `git remote`; do git push $i; done;'
  1754. // alias pullall='for i in `git remote`; do git pull $i; done;'
  1755. // args === processedArgs ? args = {} : null;
  1756. var __args = {
  1757. remotename : args.remotename|| processedArgs._[2]
  1758. , reponame : args.reponame || (args.repodef ? args.repodef.repo : undefined)
  1759. , url : args.url || processedArgs._[3]
  1760. , branch : args.branch || processedArgs._[4] || 'master'
  1761. }
  1762. __args.upstream = args['upstream'] || processedArgs._[5] || `${remotename}/${branch}`
  1763. var remotename = __args.remotename
  1764. var url = __args.url
  1765. var branch = __args.branch
  1766. var upstream = __args.upstream
  1767. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1768. var serial_perform_git_add = (reponame) => {
  1769. var options = { cwd: instanceroot + '/' + reponame }
  1770. // console.log(reponame)
  1771. if (pushable) {
  1772. var gacmds = [
  1773. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1774. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1775. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1776. ]
  1777. }
  1778. else {
  1779. var gacmds = [
  1780. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1781. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }]
  1782. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1783. // When we add a remote it should not automatically become the upstream. The upstream should be a chosen remote else we do not change
  1784. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1785. ]
  1786. }
  1787. if(__args['upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1788. return gacmds
  1789. }
  1790. // PB : TODO -- Accumulate using yield... and finally return a set of tasks or promises...
  1791. var perform_git_add = (dir) => {
  1792. return oplist['is-git-repo'](dir).then((logEntry) => {
  1793. // console.log(code)
  1794. if (logEntry.success) {
  1795. return nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1796. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  1797. return remotename;
  1798. })
  1799. .catch((e) => {
  1800. return perform( serial_perform_git_add, dir.name ).then(()=>{
  1801. return remotename
  1802. })
  1803. })
  1804. }
  1805. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1806. }).catch((e) => {
  1807. console.log('Failed : ' + dir.name)
  1808. })
  1809. }
  1810. if(__args.reponame) { return perform_git_add( { name : __args.reponame} ) }
  1811. else return dirs(perform_git_add)
  1812. }
  1813. , 'remote remove': (args) => {
  1814. var __args = {
  1815. remotename : args.remotename|| processedArgs._[2]
  1816. }
  1817. var remotename = __args.remotename
  1818. var serial_perform_git_remove = (repo) => {
  1819. var options = { cwd: instanceroot + '/' + repo }
  1820. // console.log(repo)
  1821. return [
  1822. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  1823. ]
  1824. }
  1825. var perform_git_remove = (dir) => {
  1826. oplist['is-git-repo'](dir).then((logEntry) => {
  1827. // console.log(code)
  1828. if (logEntry.success) {
  1829. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1830. any(serial_perform_git_remove(dir.name).map(getnodeshellexectask))
  1831. })
  1832. .catch((e) => {
  1833. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  1834. })
  1835. }
  1836. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1837. }).catch((e) => {
  1838. // console.log('Failed : ' + dir.name)
  1839. })
  1840. }
  1841. dirs(perform_git_remove)
  1842. }
  1843. , 'get-remotes' : (args) => {
  1844. // var __args = {
  1845. // repo : args?.repo || processedArgs._[1]
  1846. // }
  1847. // git branch -r | grep -v '\->' | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
  1848. var repo = args.repo
  1849. var serial_perform = (repo) => {
  1850. return [
  1851. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1852. evaluateResult : function( issuccess, result){
  1853. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1854. var lines = result.messages.join('').split('\n')
  1855. var remotes = {}
  1856. lines.forEach(line => {
  1857. // pattern = origin https://git.bbh.org.in/chess/elxr (fetch)
  1858. var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line)
  1859. if(match) {
  1860. var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] })
  1861. if(match[3] === 'push') { r.push = match[2] }
  1862. else r.url = match[2]
  1863. }
  1864. })
  1865. return remotes
  1866. }}]
  1867. ]
  1868. }
  1869. return perform( serial_perform, repo )
  1870. }
  1871. , 'get-remote' : (upstream) => {
  1872. // var __args = {
  1873. // repo : args?.repo || processedArgs._[1]
  1874. // }
  1875. var repo = upstream.repo
  1876. var serial_perform = (repo) => {
  1877. return [
  1878. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1879. evaluateResult : function( issuccess, result){
  1880. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1881. // origin https://git.bbh.org.in/chess/elxr (fetch)
  1882. var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '))
  1883. if(match) { upstream.url = match[1] }
  1884. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1885. return upstream
  1886. }}]
  1887. ]
  1888. }
  1889. return perform( serial_perform, repo )
  1890. }
  1891. , 'get-upstream' : (args) => {
  1892. var __args = {
  1893. repo : args?.repo || processedArgs._[1]
  1894. }
  1895. var repo = __args.repo
  1896. var serial_perform = (repo) => {
  1897. return [
  1898. ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1899. evaluateResult : function( issuccess, result){
  1900. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1901. var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '))
  1902. if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] } }
  1903. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1904. if(args?.remotes) {
  1905. var r = args.remotes[upstream.remotename];
  1906. if(!r) return oplist['get-remote'](upstream)
  1907. r.branch = upstream.branch
  1908. r.remotebranch = upstream.remotebranch
  1909. return r
  1910. }
  1911. return oplist['get-remote'](upstream)
  1912. }}]
  1913. ]
  1914. }
  1915. return perform( serial_perform, repo )
  1916. }
  1917. , 'init-gitea': (username) => {
  1918. // Change user to an object that has user.username and use here..
  1919. username = username || processedArgs._[1]
  1920. if (!username) throw 'User name required'
  1921. var serial_perform_init_gitea = (repo) => {
  1922. var options = { cwd: instanceroot + '/' + repo }
  1923. // console.log(repo)
  1924. return [
  1925. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  1926. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  1927. , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  1928. ]
  1929. }
  1930. var perform_init_gitea = (dir) => {
  1931. oplist['is-git-repo'](dir).then((logEntry) => {
  1932. // console.log(code)
  1933. if (logEntry.success) {
  1934. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1935. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  1936. })
  1937. .catch((e) => {
  1938. perform( serial_perform_init_gitea, dir.name )
  1939. })
  1940. }
  1941. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1942. }).catch((e) => {
  1943. // console.log('Failed : ' + dir.name)
  1944. })
  1945. }
  1946. dirs(perform_init_gitea)
  1947. }
  1948. , 'syncmaster': (label) => {
  1949. // Usage :
  1950. // elxr pull -- Defaults to run config
  1951. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1952. if (!processedArgs.runas) gitRepos.map((def) => {
  1953. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1954. else performPullOrClone(def, def.branch || 'master')
  1955. })
  1956. var etask = ()=>{
  1957. return any(elevatedRunasRepos.map((def) =>
  1958. {
  1959. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1960. else performPullOrClone(def, def.branch || 'master')
  1961. })).then(() => {
  1962. fs.writeFileSync('run.done', 'success')
  1963. }).catch(() => {
  1964. fs.writeFileSync('run.done', 'error')
  1965. })
  1966. }
  1967. etask.statuslog = statuslog
  1968. etask.selectedinstance = selectedinstance
  1969. etask.processedArgs = processedArgs
  1970. etask.runtimestamp = runtimestamp
  1971. etask.ENV = ENV
  1972. return shell_verse.runElevated(etask)
  1973. }
  1974. , 'repo-relocate' : function(args){
  1975. // relocate a subfolder in source repo to same subfolder in target repo with history.
  1976. args = ARGUMENTVALIDATOR.validate( args, { sourcerepo : true, targetrepo : true, remotebase : true }, {}, {
  1977. remotebase : processedArgs._[5] || 'http://git.bbh'
  1978. , folder : processedArgs._[3] || '' //|| 'server'
  1979. , targetfolder : processedArgs._[4] || ''
  1980. , sourcerepo : processedArgs._[2]
  1981. , targetrepo : processedArgs._[1]
  1982. , repodir : `${processedArgs._[6] || instanceroot}` /*workingroot for this command...*/ || `${instanceroot}/relocate` // Default workingroot figure out a way to pass it in.
  1983. , branch : 'master'
  1984. } )
  1985. var sourcerepooptions = { cwd: args.repodir
  1986. // , stdio: ['pipe', process.stdout, process.stderr]
  1987. , inherit: true,
  1988. shell: true,
  1989. env: ENV
  1990. , runas: processedArgs.runas
  1991. }
  1992. return oplist['repo-split'](args).then(()=>{
  1993. return oplist['repo-merge'](args).then(()=>{
  1994. // cleanup folder from source.
  1995. var cmdseq = [
  1996. // ['rm', ['-rf', `${args.repodir}`], sourcerepooptions ]
  1997. // ['rm', ['-rf', `${args.sourcerepo}`], sourcerepooptions ]
  1998. // commits have to be intentional...
  1999. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  2000. ]
  2001. return any(cmdseq.map(getshelltask))
  2002. })
  2003. }).catch(e=>{console.error(e)})
  2004. }
  2005. , 'repo-split' : function(args) {
  2006. // https://gist.github.com/smdabdoub/17065c348289158277b5
  2007. /**
  2008. * Eg : folder, remotebase, sourcerepo, targetrepo
  2009. * args.folder = 'server'
  2010. * args.remotebase = 'https://git.bbh/chess/'
  2011. * args.sourcerepo = 'client'
  2012. * args.targetrepo = 'elixir-server'
  2013. */
  2014. var currentargs = ARGUMENTVALIDATOR.validate( args, { repodir : true, remotebase : true }, {}, {
  2015. // remotebase : 'http://git.bbh' + `/${getowner(args)}`
  2016. folder : '' //'server' // Do all folders by default.
  2017. , targetfolder : ''
  2018. , sourcerepo : undefined
  2019. , targetrepo : undefined
  2020. // , repodir : .. should be passed in.
  2021. } )
  2022. // var options = { cwd: args.repodir
  2023. // // , stdio: ['pipe', process.stdout, process.stderr]
  2024. // , inherit: true,
  2025. // shell: true,
  2026. // env: ENV
  2027. // , runas: processedArgs.runas
  2028. // }
  2029. currentargs.sourceloc = args.folder ? `relocatesource-${args.sourcerepo}-${args.folder}` : `relocatesource-${args.sourcerepo}`
  2030. currentargs.targetloc = args.targetfolder ? `relocatetarget-${args.targetrepo}-${args.targetfolder}` : `relocatetarget-${args.targetrepo}`
  2031. currentargs.repodir = args.repodir + '/relocate/' + currentargs.sourceloc + `/${args.owner || defaultowner}`
  2032. currentargs.repo = args.sourcerepo
  2033. currentargs = utils.assign({}, args, currentargs)
  2034. currentargs.remotebase = (args.remotebase || 'http://git.bbh') + `/${getowner(args)}`
  2035. // console.dir(GITSHELL.pullORcloneSHELLCMD( currentargs ))
  2036. var cmdseq = [
  2037. // create a temporary working dir in current folder where we started execution.
  2038. getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', 'relocate/' + currentargs.sourceloc + `/${getowner(args)}`] ]) ]
  2039. , { cwd: args.repodir
  2040. // , stdio: ['pipe', process.stdout, process.stderr]
  2041. , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
  2042. }])
  2043. // This copy is needed to manually delete the relocated folder / repo and commit. ( Tool will not autocommit )
  2044. // , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  2045. , GITSHELL.pullORcloneSHELLCMD( currentargs )
  2046. // This is where the source will get split.
  2047. , getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', currentargs.sourceloc + '-split' + `/${getowner(args)}` ] ]) ]
  2048. , { cwd: args.repodir + '/relocate'
  2049. // , stdio: ['pipe', process.stdout, process.stderr]
  2050. , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
  2051. }])
  2052. // , ['git', ['clone', `${args.sourcerepo}`, args.sourceloc], utils.assign({}, options, {cwd: args.sourceloc} ) ]
  2053. , GITSHELL.pullORcloneSHELLCMD( utils.assign({}, currentargs, { remotebase : '../../' + currentargs.sourceloc + `/${getowner(args)}`
  2054. , targetloc : '.'
  2055. , repodir : args.repodir + '/relocate/' + currentargs.sourceloc + '-split' + `/${getowner(args)}`
  2056. , localrepo :true
  2057. }))
  2058. // This is where the target will have the merged folder. ( Tool will not autocommit )
  2059. // // , ['git', ['clone', `${args.remotebase}${args.targetrepo}`], utils.assign({}, options, {cwd: args.targetloc} )]
  2060. , getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', currentargs.targetloc + `/${getowner(args)}`] ]) ]
  2061. , { cwd: args.repodir + '/relocate'
  2062. // , stdio: ['pipe', process.stdout, process.stderr]
  2063. , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
  2064. }])
  2065. , GITSHELL.pullORcloneSHELLCMD( utils.assign({ requiresElevation : true }, currentargs, { repo : args.targetrepo
  2066. , repodir : path.normalize(args.repodir + '/relocate/' + currentargs.targetloc) + `/${getowner(args)}` }) )
  2067. ]
  2068. return any(cmdseq).then(() => {
  2069. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2070. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  2071. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2072. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  2073. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  2074. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  2075. // subtree split and filter-branch are options. We currently use repo-filter.
  2076. currentargs.repodir = args.repodir + '/relocate/' + currentargs.sourceloc + '-split' + `/${getowner(args)}/${currentargs.repo}`
  2077. return oplist['filter-repo'](currentargs)
  2078. }).catch(e=>{
  2079. console.error(e);
  2080. throw 'failed'
  2081. })
  2082. }
  2083. , 'repo-merge' : function(args) {
  2084. // Merge source repo into target repo
  2085. var currentargs = ARGUMENTVALIDATOR.validate( args, { repodir : true, remotebase : true }, {}, {
  2086. remotebase : 'http://git.bbh'
  2087. , folder : '' //'server' // Do all folders by default.
  2088. , targetfolder : ''
  2089. , sourcerepo : undefined
  2090. , targetrepo : undefined
  2091. // , repodir : .. should be passed in.
  2092. } )
  2093. // var options = { cwd: args.repodir
  2094. // // , stdio: ['pipe', process.stdout, process.stderr]
  2095. // , inherit: true,
  2096. // shell: true,
  2097. // env: ENV
  2098. // , runas: processedArgs.runas
  2099. // }
  2100. currentargs.sourceloc = args.folder ? `relocatesource-${args.sourcerepo}-${args.folder}` : `relocatesource-${args.sourcerepo}`
  2101. currentargs.targetloc = args.targetfolder ? `relocatetarget-${args.targetrepo}-${args.targetfolder}` : `relocatetarget-${args.targetrepo}`
  2102. currentargs.repodir = args.repodir + '/' + currentargs.sourceloc
  2103. currentargs.repo = args.sourcerepo
  2104. currentargs = utils.assign({}, args, currentargs)
  2105. var targetrepooptions = { cwd: args.repodir + '/relocate/' + currentargs.targetloc + `/${args.owner || defaultowner}` + `/${args.targetrepo}`
  2106. // , stdio: ['pipe', process.stdout, process.stderr]
  2107. , inherit: true,
  2108. shell: true,
  2109. env: ENV
  2110. , runas: processedArgs.runas
  2111. }
  2112. // git pull ../../../relocatesource-client-split/chess/client master --allow-unrelated-histories
  2113. var cmdseq = [
  2114. ['git', ['pull', `../../../` + currentargs.sourceloc + '-split' + `/${args.owner || defaultowner}` + `/${args.sourcerepo}`, `master`, '--allow-unrelated-histories']
  2115. , targetrepooptions ]
  2116. // , ['git', ['push', targetrepooptions ] // manual push for now..
  2117. ]
  2118. return any(cmdseq.map(getshelltask)).catch(e=>{console.error( JSON.stringify(e) ) })
  2119. }
  2120. , 'filter-repo' : function(args){
  2121. // Use a temp fresh new local copy of any source repo in a temp location and filter out other portions of the repo that we are not relocating.
  2122. var args = args || {
  2123. folder : '' // 'server'
  2124. , targetfolder : ''
  2125. , remotebase : 'http://git.bbh'
  2126. , targetrepo : undefined
  2127. }
  2128. args = ARGUMENTVALIDATOR.validate( args, { sourcerepo : true, repodir : true, sourceloc : true }, {}, {
  2129. remotebase : 'http://git.bbh'
  2130. , folder : '' //'server' // Do all folders by default.
  2131. , targetfolder : ''
  2132. , sourcerepo : undefined
  2133. , targetrepo : undefined
  2134. // , repodir : .. should be passed in.
  2135. } )
  2136. var sourcerepooptions = { cwd: args.repodir
  2137. // , stdio: ['pipe', process.stdout, process.stderr]
  2138. , inherit: true, shell: true, env: ENV
  2139. , runas: processedArgs.runas
  2140. }
  2141. var cmdargs = (args.targetfolder && args.folder) ? ['filter-repo', '--force', '--path', `${args.folder}` , `--path-rename :${args.targetfolder}/` ]
  2142. : args.targetfolder ? ['filter-repo', '--force',`--path-rename :${args.targetfolder}/` ]
  2143. : args.folder ? ['filter-repo', '--force','--path', `${args.folder}` ] : ['filter-repo', '--force']
  2144. var cmdseq = [
  2145. // git checkout -b feature/merge-old-project
  2146. // git remote add src-project ../src-project
  2147. ['git', cmdargs, sourcerepooptions ]
  2148. ]
  2149. console.dir(args.targetfolder)
  2150. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  2151. }
  2152. , 'filter-branch' : function(preservefolder, repo){
  2153. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  2154. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  2155. // Preserve a specific folder.
  2156. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  2157. /*
  2158. git clone repo reposplit
  2159. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  2160. git remote rm origin
  2161. */
  2162. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  2163. }
  2164. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  2165. // // Merge repo2 into a subfolder in repo1
  2166. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  2167. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  2168. // /*
  2169. // cd repo1
  2170. // git remote add -f tempmergesource ../{{mergesource}}/.git
  2171. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  2172. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  2173. // git commit
  2174. // // Repair History
  2175. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  2176. // #!/usr/bin/env bash
  2177. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  2178. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  2179. // subdir=server
  2180. // git filter-branch --tree-filter '
  2181. // first='"$first"'
  2182. // last='"$last"'
  2183. // subdir='"$subdir"'
  2184. // log_file=/tmp/filter.log
  2185. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  2186. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  2187. // echo "=== $GIT_COMMIT: making changes"
  2188. // files=$(git ls-tree --name-only $GIT_COMMIT)y
  2189. // mkdir -p $subdir
  2190. // for i in $files; do
  2191. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  2192. // done
  2193. // else
  2194. // echo "=== $GIT_COMMIT: ignoring"
  2195. // fi \
  2196. // >> $log_file
  2197. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  2198. // status=0 # tell tree-filter never to fail
  2199. // '
  2200. // git remote rm tempmergesource
  2201. // */
  2202. // // better alternative for history
  2203. // /**
  2204. // *
  2205. // git clone git@server.com:old-project.git
  2206. // git clone git@server.com:new-project.git
  2207. // cd old-project
  2208. // mkdir old-project
  2209. // git mv !(old-project) old-project
  2210. // ls -la and gt mv hidden files ....
  2211. // git commit -a -S -m “Moving old project into its own subdirectory”
  2212. // cd ../new-project
  2213. // git remote add old-project ../old-project
  2214. // git fetch old-project
  2215. // git checkout -b feature/merge-old-project
  2216. // git merge -S --allow-unrelated-histories old-project/master
  2217. // git push origin feature/merge-old-project
  2218. // git remote rm old-project
  2219. // */
  2220. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  2221. // }
  2222. , 'clone' : (label) =>{
  2223. return elxr.getPullOrCloneTask(selectedinstance)
  2224. }
  2225. , 'pull' : (label) => {
  2226. // Usage :
  2227. // elxr pull -- Defaults to run config
  2228. return elxr.getPullOrCloneTask(selectedinstance)
  2229. }
  2230. , 'isInstalled': () => {
  2231. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  2232. console.log(processedArgs._[1] + ' exists.')
  2233. return true;
  2234. });
  2235. }
  2236. , 'c' : ()=>{
  2237. }
  2238. , 'i' : () => {
  2239. var tasks = []
  2240. // tasks.push(oplist['pull']);
  2241. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  2242. tasks.push(oplist['use']) // Will pull repos...
  2243. oplist['npmi'].statuslog = statuslog
  2244. tasks.push(shell_verse.getNonElevatedTask(oplist['npmi'])) // We do not run npm i with elevated privilege for security reasons.
  2245. // var tasksdefs = [
  2246. // ['elxr', ['pull']]
  2247. // , ['elxr', ['use', 'elixir']]
  2248. // , ['elxr', ['npmi']]
  2249. // ]
  2250. // tasksdefs.forEach(tasksdef=>{
  2251. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  2252. // })
  2253. return any(tasks);
  2254. }
  2255. , 'npmi': () => {
  2256. var tasks = [];
  2257. // Build fails without babel...
  2258. tasks.push(getShellTask(
  2259. 'npm',[ 'i', '-g', 'babel-cli' ]
  2260. ) )
  2261. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  2262. // npmbuildrepos = []
  2263. npmbuildrepos.forEach(repo => {
  2264. tasks.push(() => {
  2265. return nodeShellExec('npm', ['i --force'], {
  2266. inherit: true, shell: true
  2267. , cwd: instanceroot + '/' + repo
  2268. , env: ENV
  2269. , title: `npm i for ${repo}`
  2270. }).catch((e) => {
  2271. console.error('Ignoring Benign Error'); console.error(util.inspect(e));
  2272. }).then(() => {
  2273. console.log(`--npm run build for ${repo}--------------------`)
  2274. return nodeShellExec('npm', ['run build'], {
  2275. inherit: true, shell: true
  2276. , cwd: instanceroot + '/' + repo
  2277. , env: ENV
  2278. , title: `npm run build for ${repo}`
  2279. }).then(Tasq.then).catch(Tasq.catch)
  2280. })
  2281. })
  2282. })
  2283. return any(tasks).then(() => {
  2284. gitRepos.push({ repo : 'chess-server-lib/server'});
  2285. gitRepos = gitRepos.concat(elevatedRunasRepos);
  2286. // console.dir(gitRepos)
  2287. // throw ""
  2288. // gitRepos = [
  2289. // // 'bbhverse', 'serververse', 'elixir-server',
  2290. // // 'clientverse',
  2291. // 'client'
  2292. // ];
  2293. var rmtasks = []
  2294. var repotasks = []
  2295. var env = Object.assign({}, ENV)
  2296. delete env.NODE_ENV // PB : TODO -- Why delete ??? npm i fails with NODE_ENV...
  2297. gitRepos.forEach(repodef => {
  2298. rmtasks.push(
  2299. // () => {
  2300. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2301. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  2302. callshelltask(['rm', ['package-lock.json'], {
  2303. inherit: true, shell: true
  2304. , cwd: instanceroot + '/' + repodef.repo
  2305. , env: ENV
  2306. , title: `rm 'package-lock.json' for ${repodef.repo}`
  2307. }])
  2308. .then(()=>{
  2309. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2310. }).catch((e) => { console.error(util.inspect(e)) })
  2311. // }
  2312. )
  2313. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  2314. repotasks.push(
  2315. () => {
  2316. console.log(`--npm i for ${repodef.repo}--------------------`)
  2317. var p = nodeShellExec('npm', ['i', '--force'], {
  2318. inherit: true, shell: true
  2319. , cwd: instanceroot + '/' + repodef.repo
  2320. , env
  2321. , title: `npm i for ${repodef.repo}`
  2322. }).then(Tasq.then).catch(Tasq.catch)
  2323. return p;
  2324. })
  2325. }
  2326. })
  2327. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  2328. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  2329. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  2330. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  2331. // PB : TODO -- Investigate why NODE_ENV has an impact on npm i !??
  2332. // Second time try also doesnt work.
  2333. // repotasks.push(
  2334. // () => {
  2335. // var env = Object.assign({}, process.env)
  2336. // delete env.NODE_ENV
  2337. // console.log(`--------------------second time npm i for client--------------------`)
  2338. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  2339. // // return nodeShellExec('npm', ['i --force'], {
  2340. // inherit: true, shell: true
  2341. // , cwd: instanceroot + '/' + 'client'
  2342. // , env
  2343. // , title: `npm i for client`
  2344. // }).then(Tasq.then).catch(Tasq.catch)
  2345. // })
  2346. var bowerRepos = [{ repo : 'elixir-client/client'}];
  2347. var bowertasks = []
  2348. bowerRepos.forEach(repodef => {
  2349. bowertasks.push(() => {
  2350. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  2351. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  2352. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  2353. inherit: true, shell: true
  2354. , cwd: instanceroot + '/' + repodef.repo
  2355. , env: ENV
  2356. , title: `bower i for ${repodef.repo}`
  2357. }).then(Tasq.then).catch(Tasq.catch)
  2358. return p;
  2359. })
  2360. })
  2361. // console.log('rmtasks.length : ' + rmtasks.length)
  2362. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  2363. }).catch(e => {
  2364. console.error(e)
  2365. }).finally(statuslog.finally)
  2366. }
  2367. , 'start': (args) => {
  2368. // Usage : elxr start {{instanceName=elixir}} {{all||server||client||{{microserviceName=elixir||express}}}}
  2369. var label = clioverrides.cmd
  2370. var env = Object.assign({}, ENV); // Shallow clone it.
  2371. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  2372. function startFn( o ){
  2373. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  2374. console.log(`Starting ${o.name}.`);
  2375. if(shell_verse.isWin()){
  2376. var __cmd = 'cmd'
  2377. var a1 = '/k'
  2378. }
  2379. else if(shell_verse.islin()) {
  2380. var __cmd = 'sh'
  2381. var a1 = '-c'
  2382. }
  2383. if(o.cmd) {
  2384. cmd = o.cmd
  2385. var childPromise = nodeShellExec(...o.cmd, {
  2386. // inherit : true,
  2387. shell: true,
  2388. detached: true,
  2389. stdio: 'ignore',
  2390. cwd: instanceroot + o.path
  2391. , env
  2392. })
  2393. }
  2394. else {
  2395. var childPromise = nodeShellExec(__cmd, [a1, getCmdString(cmd) ], {
  2396. // inherit : true,
  2397. shell: true,
  2398. detached: true,
  2399. stdio: 'ignore',
  2400. cwd: instanceroot + o.path
  2401. , env
  2402. })
  2403. }
  2404. var child = childPromise.process;
  2405. var cpid = child.pid
  2406. childPromise.then(()=>{
  2407. console.log(` *** started ${o.name} PID(${cpid}) ${cmd}`);
  2408. fs.writeFileSync(o.pidstore, '' + cpid)
  2409. })
  2410. .catch(e => console.error(e) )
  2411. }
  2412. if(clioverrides.node_env === 'development') {
  2413. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  2414. if(!processedArgs._[2]) processedArgs._[2] = 'all'
  2415. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2416. || processedArgs._[2] === 'elixir' // specific microservice name.
  2417. ) {
  2418. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server'
  2419. , pidstore : '.elixir-server.elixir.server.pid'
  2420. } )
  2421. }
  2422. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2423. || processedArgs._[2] === 'express' // specific microservice name.
  2424. ) {
  2425. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server'
  2426. , pidstore : '.express.server.pid'
  2427. } )
  2428. }
  2429. if(processedArgs._[2] === 'client' || processedArgs._[2] === 'all') {
  2430. startFn( {
  2431. name : 'Elixir Ember Client', path : '/' + 'client'
  2432. , cmd : ['node_modules/ember-cli/bin/ember', ['s']]
  2433. , pidstore : '.client.server.pid'
  2434. } )
  2435. }
  2436. }
  2437. }
  2438. , 'stop': (label) => {
  2439. const kill = require('tree-kill');
  2440. try{
  2441. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8'})
  2442. fs.unlinkSync('.elixir-server.elixir.server.pid')
  2443. console.log(serverPid)
  2444. kill(serverPid)
  2445. }
  2446. catch(e){ console.error(e) }
  2447. try{
  2448. serverPid = fs.readFileSync('.express.server.pid', { encoding: 'utf8' })
  2449. fs.unlinkSync('.express.server.pid')
  2450. console.log(serverPid)
  2451. kill(serverPid)
  2452. }
  2453. catch(e){ console.error(e) }
  2454. try{
  2455. serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' })
  2456. fs.unlinkSync('.client.server.pid')
  2457. console.log(serverPid)
  2458. kill(serverPid)
  2459. }
  2460. catch(e){ console.error(e) }
  2461. }
  2462. , 'model' : () => {
  2463. var etask = ()=>{
  2464. var tasks = [
  2465. () => {
  2466. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  2467. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  2468. inherit: true, shell: true
  2469. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  2470. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  2471. , env: ENV
  2472. }).catch((e) => { console.error(e) })
  2473. return p;
  2474. }
  2475. ];
  2476. return any(tasks).then(() => {
  2477. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  2478. }).catch(() => {
  2479. fs.writeFileSync('run.done', 'error')
  2480. })
  2481. }
  2482. etask.statuslog = statuslog
  2483. etask.selectedinstance = selectedinstance
  2484. etask.processedArgs = processedArgs
  2485. etask.runtimestamp = runtimestamp
  2486. etask.ENV = ENV
  2487. return shell_verse.runElevated(etask)
  2488. }
  2489. , 'use' : () => {
  2490. // use a certain named instance.
  2491. // Eg :
  2492. // 1) elxr use elixir
  2493. // 2) elxr use cihsr
  2494. // If environment is not specified defaults to development.
  2495. // 1) NODE=test elxr use elixir
  2496. /*// Steps
  2497. 1) Delete Config and Data symlinks
  2498. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  2499. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  2500. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2501. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  2502. */
  2503. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  2504. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  2505. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  2506. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  2507. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  2508. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') } // PB : TODO -- IPC through files is needed only for windows.
  2509. if (existsSync('config') && existsSync('data')){
  2510. return
  2511. }
  2512. }
  2513. var tasks = [
  2514. () => {
  2515. var promise = new Promise((resolve, reject)=>{
  2516. existslink('config', function(err, data){
  2517. if(data) {
  2518. var p = shell_verse.removeJuncionOrLink('config')
  2519. .then(()=>{resolve(true)})
  2520. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2521. }
  2522. else resolve(false)
  2523. })
  2524. })
  2525. return promise;
  2526. },
  2527. () => {
  2528. var promise = new Promise((resolve, reject)=>{
  2529. existslink('data', function(err, data){
  2530. if(data) {
  2531. var p = shell_verse.removeJuncionOrLink('data')
  2532. .then(()=>{resolve(true)})
  2533. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2534. }
  2535. else resolve(false)
  2536. })
  2537. })
  2538. return promise;
  2539. },
  2540. ];
  2541. runconfig.NODE_ENV = ENV.NODE_ENV = ENV.NODE_ENV || runconfig.NODE_ENV || 'development';
  2542. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  2543. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  2544. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  2545. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  2546. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  2547. var performPullOrCloneOrCloneForBranch = (def)=>{
  2548. var promise = Promise.resolve(true)
  2549. if (!branch) {
  2550. var dscoverbranchcmd = gitops.getdiscoverbranchcmd({ repo, repodir : instanceroot})
  2551. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  2552. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2553. }
  2554. return promise.then(()=>{ return elxr.getPullOrCloneTask(def)() }).catch(e => { console.error( 'performPullOrCloneOrCloneForBranch : Failed ' + e )})
  2555. }
  2556. var performCloneAndCheckout = null;
  2557. // cant use git checkout -b it fails when branch already exists.
  2558. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2559. return performPullOrCloneOrCloneForBranch(def).then(()=>{
  2560. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2561. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2562. // inherit : true, shell: true,
  2563. cwd: instanceroot + '/' + def.repo
  2564. // , stdio : ignore // Use when we want to silence output completely.
  2565. , runas: processedArgs.runas
  2566. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  2567. }).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 } })
  2568. })
  2569. }
  2570. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  2571. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  2572. var elevatedqueue = [];
  2573. var enqueueOnce = (queue, task, def) => {
  2574. var found = queue.find(element => {
  2575. var keys = Object.keys( element )
  2576. for(var k=0; k < keys.length; k++) {
  2577. if(element[keys[k]] !== def[k]) return false;
  2578. }
  2579. })
  2580. queue.push(function(){ return task(this)}.bind(def));
  2581. }
  2582. var enqueue = (queue, task, def) => {
  2583. queue.push(function(){ return task(def)}.bind(def));
  2584. }
  2585. var mergeSources = {
  2586. 'development': null,
  2587. 'test': 'master',
  2588. 'production': 'master'
  2589. }
  2590. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2591. // Checkout is reduced to pull provided the current branch is the targetbranch
  2592. if(branch === mergesource) performCheckout = (def) => {
  2593. var dscoverbranchcmd = gitops.getdiscoverbranchcmd({ repo, repodir : instanceroot})
  2594. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  2595. if(branch === __branch) return performCloneAndCheckout(def)
  2596. return performPullOrCloneOrCloneForBranch(def)
  2597. })
  2598. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2599. }
  2600. // else performCheckout = (def) => { return performPullOrCloneOrCloneForBranch(def) }
  2601. var performPullOrCloneAll = (def) => {
  2602. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2603. return nodeShellExec('git', ['pull', '--all'], {
  2604. // inherit : true, shell: true,
  2605. cwd: instanceroot + '/' + def.repo
  2606. , runas: processedArgs.runas
  2607. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  2608. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  2609. }
  2610. var excludeCheckouts = Object.assign(exludeMergeRepos)
  2611. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  2612. // delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  2613. var performMerge = (def) => {
  2614. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2615. return nodeShellExec('git', ['merge', mergesource], {
  2616. inherit: true, shell: true,
  2617. cwd: instanceroot + '/' + def.repo
  2618. , runas: processedArgs.runas
  2619. }).catch((e) => { console.error(e) })
  2620. }
  2621. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  2622. // var performRepoOperation = function(def) {
  2623. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  2624. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  2625. // }
  2626. return any(tasks).then(() => {
  2627. var task = ()=>{
  2628. // Default target is developent. if some other target is specified in NODE_ENV in for shell call for the 'use' command we will switch to that target..
  2629. //Switch to target branch
  2630. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  2631. // pull or clone target branch
  2632. .then(() => {
  2633. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2634. return any(gitRepos.map((repo) => performPullOrCloneAll(repo)))
  2635. })
  2636. // switch to source branch
  2637. .then( () => {
  2638. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  2639. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  2640. })
  2641. //Pull on merge source branch
  2642. .then( () => {
  2643. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2644. return any(gitRepos.map((repo) => performPullOrCloneAll(repo)))
  2645. })
  2646. //Switch to target branch
  2647. .then( () => {
  2648. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2649. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  2650. })
  2651. .then( //Merge source branch to target branch
  2652. () => {
  2653. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2654. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  2655. })
  2656. }
  2657. task.statuslog = statuslog
  2658. var netask = shell_verse.getNonElevatedTask(task)
  2659. var eltask = ()=> {
  2660. var opts = {
  2661. inherit: true, shell: true
  2662. , cwd : instanceroot
  2663. , env: ENV
  2664. }
  2665. var tasks = [
  2666. () => {
  2667. // Use junctions to avoid npm package issues
  2668. var target = runconfig.use + '-' + 'config' + '-' + ENV.NODE_ENV
  2669. var p = shell_verse.createJuntionOrLink('config', target, opts)
  2670. return p;
  2671. }
  2672. , () => {
  2673. // Use junctions to avoid npm package issues
  2674. var target = runconfig.use + '-' + 'clientconfig' + '-' + ENV.NODE_ENV
  2675. var p = shell_verse.createJuntionOrLink('clientconfig', target, opts)
  2676. return p;
  2677. }
  2678. ];
  2679. // if (processedArgs._[1]) {
  2680. tasks = tasks.concat( [
  2681. () => {
  2682. var dataToLink = runconfig.use + '-data' + '-' + ENV.NODE_ENV
  2683. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  2684. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  2685. return p;
  2686. }
  2687. ]
  2688. )
  2689. // }
  2690. return any(tasks).then(()=>{
  2691. // checkout target branch
  2692. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2693. // pull or clone target branch
  2694. .then(() => {
  2695. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2696. return any(elevatedRunasRepos.map((repo) => performPullOrCloneAll(repo)))
  2697. })
  2698. // switch to source branch
  2699. .then( () => {
  2700. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2701. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  2702. })
  2703. //Pull on merge source branch
  2704. .then( () => {
  2705. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2706. return any(elevatedRunasRepos.map((repodef) => performPullOrCloneAll({repo : repodef.repo, requiresElevation : true })))
  2707. })
  2708. //Switch to target branch
  2709. .then( () => {
  2710. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2711. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2712. })
  2713. .then( //Merge source branch to target branch
  2714. () => {
  2715. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2716. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  2717. })
  2718. .then(() => {
  2719. fs.writeFileSync('run.done', 'success')
  2720. }).catch(() => {
  2721. fs.writeFileSync('run.done', 'error')
  2722. })
  2723. })
  2724. }
  2725. eltask.statuslog = statuslog
  2726. eltask.selectedinstance = selectedinstance
  2727. eltask.processedArgs = processedArgs
  2728. eltask.runtimestamp = runtimestamp
  2729. var eltask = shell_verse.getElevatedTask(eltask)
  2730. return eltask().then( ()=>{ return netask() })
  2731. }).catch((e) => {
  2732. fs.writeFileSync('run.done', 'error : ' + e)
  2733. })
  2734. // Antibiotic stewardship program.
  2735. // 1st use is fine.
  2736. // Max vials dispense
  2737. // 2nd use Pharmacy needs justification Form.
  2738. // Approval after a certain period of time.
  2739. }
  2740. , 'g' : () => {
  2741. if (processedArgs.h) {
  2742. console.log('elxr g model [modelname] => generate a model named [modelname]');
  2743. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  2744. console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
  2745. console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
  2746. console.log('elxr g => regenerate all known models');
  2747. return
  2748. }
  2749. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  2750. // try {
  2751. // child = child.on('close', () => { process.chdir(label) } );
  2752. // }
  2753. // catch (err) {
  2754. // console.log('chdir: ' + err);
  2755. // }
  2756. // child.on('close', function(){
  2757. // var options = {
  2758. // shell : true
  2759. // , inherit : true
  2760. // // , cwd : '' + process.cwd
  2761. // // , env : ENV
  2762. // };
  2763. // nodeShellExec('git', ['init'], { inherit : true});
  2764. if (0) {
  2765. // PB : TODO -- Special google chrome profile for tests etc.
  2766. nodeShellExec('pwd', { inherit: true });
  2767. // /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"
  2768. // "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
  2769. // "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
  2770. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  2771. "--profile-directory=Profile 1"
  2772. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  2773. }
  2774. // nodeShellExec('npm', ['init', '-y'], options);
  2775. // nodeShellExec('npm', ['init', '-y'], options);
  2776. // })
  2777. var g = {
  2778. 'client': () => {
  2779. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  2780. console.info('Creating new ember client named : ' + processedArgs._[2]);
  2781. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  2782. stdio: ['pipe', process.stdout, process.stderr],
  2783. inherit: true,
  2784. shell: true,
  2785. cwd: path.dirname(__dirname),
  2786. env : ENV
  2787. })
  2788. },
  2789. 'modelr': () => {
  2790. var tasks = [
  2791. () => {
  2792. var p = nodeShellExec('"ember"', [
  2793. 'g'
  2794. , 'modelr'
  2795. , processedArgs._[2]], {
  2796. inherit: true, shell: true, env: ENV
  2797. }).then(() => {
  2798. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  2799. return true;
  2800. }).catch((e) => { console.error(e) })
  2801. return p;
  2802. },
  2803. () => {
  2804. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  2805. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  2806. chromeprefs = JSON.parse(chromeprefs)
  2807. var previous = chromeprefs.download.default_directory;
  2808. var parentDir = path.dirname(__dirname);
  2809. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  2810. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2811. // PB : TODO -- detect where chrome is installed.
  2812. // PB : TODO -- set the download dir to the place where files are needed.
  2813. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  2814. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  2815. , '--profile-directory="chess"'
  2816. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  2817. inherit: true, shell: true
  2818. , env: ENV
  2819. }).then(() => {
  2820. chromeprefs.download.default_directory = previous;
  2821. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2822. return true;
  2823. }).catch((e) => { console.error(e) })
  2824. return p;
  2825. }
  2826. ,
  2827. () => {
  2828. console.log('Browser process should have closed here....')
  2829. return true;
  2830. }
  2831. ]
  2832. any(tasks)
  2833. }
  2834. , 'undefined' : ()=>{
  2835. console.warn('Are you sure you want to refresh all the models.');
  2836. throw 'NOT YET IMPLMENTED'
  2837. }
  2838. , 'vmodel' : (options)=>{
  2839. // node --inspect-brk elxr/index.js g vmodel qlabresults --server=true
  2840. options = options || {
  2841. generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
  2842. }
  2843. if(!options.generate) return 'Nothing specified for generation'
  2844. var name = processedArgs._[2];
  2845. if(!name) return 'No name specified for generation'
  2846. var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`
  2847. // var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel/__base__-server-lib/common/lib`
  2848. var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`
  2849. var destination = `${selectedinstance.root}`
  2850. // Create a tmp working copy for staging the changes.
  2851. return copyrecursive(templateverse, workingtarget).then( r => {
  2852. var base = 'chess' // -- The server base from where this instance was dervied from.
  2853. var patternsubstitutions = [
  2854. { strOrregexp : /(__name__)/g, substitutes : [name]}
  2855. , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
  2856. , { strOrregexp : /(__base__)/g, substitutes : [base]}
  2857. , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
  2858. , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']} // PB : TODO -- elixir-client etc... use a config to find the microclient..
  2859. ]
  2860. var options = { source : templateverse, target : workingtarget
  2861. , base , destinationroot : destination, workingtarget
  2862. , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions }
  2863. var actions = [
  2864. fswalk( workingtarget, options
  2865. , [ function(t, o){
  2866. // A series of tasks to be executed on each pattern in patternsubstitutions.
  2867. return any([
  2868. // PB : TODO -- Contentreplace is better addressed in memory instead of file IO so do all regexps in sequence in one shot and then rename.
  2869. ()=>{ return fscontentreplace( t, o ) }
  2870. , ()=>{ return fsrename( t, o ) }
  2871. ])
  2872. }] )
  2873. // Post process links in place.
  2874. , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
  2875. , workingtarget, null, options)
  2876. // Move to the final destination. Whole tree should move only top level folders are required.
  2877. // , () => fswalk( workingtarget, options, [ fsrename ])
  2878. // , () => dirs( ( child, src, target, options )=>{ return fs.renameSync(path.join(src, child.name), path.join(target, child.name) ) }
  2879. // , workingtarget, destination )
  2880. ]
  2881. return any(actions);
  2882. })
  2883. }
  2884. }
  2885. g[processedArgs._[1]]();
  2886. }
  2887. , 'launchui' : () => {
  2888. console.log('-----------------------------')
  2889. console.log('Launching Elxir Admin Console')
  2890. console.log('-----------------------------')
  2891. // shell_verse.getchrome()
  2892. processedArgs.awaitrun = true;
  2893. return shell_verse.launchui()
  2894. // shell_verse.getchrome().then( chrome => {
  2895. // nodeShellExec( `"${chrome}"`, [
  2896. // '--profile-directory="chess"'
  2897. // , `${selectedinstance.root}/elixir-client/elxr-admin-console/html/index.html`], {
  2898. // inherit: true, shell: true
  2899. // , env: ENV
  2900. // })
  2901. // .catch(e => console.dir(e))
  2902. // })
  2903. }
  2904. , 'create' : () => { return createInstance(selectedinstance) }
  2905. , 'httpget' : () => {
  2906. // RESTAPI.get({
  2907. // hostname: 'git.bbh',
  2908. // // port: 443,
  2909. // protocol : 'http:',
  2910. // path: '/',
  2911. // method: 'GET'
  2912. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  2913. return createInstance(selectedinstance)
  2914. }
  2915. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  2916. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  2917. }
  2918. var gitops = {
  2919. getdiscoverbranchcmd : function(repodef){
  2920. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  2921. var cmd = [gitbash
  2922. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  2923. , { cwd: repodef.repodir + '/' + repodef.repo, title: 'discoverbranch for ' + repodef.repo + ' ' + parameters.join(' ') }]
  2924. return cmd
  2925. }
  2926. }
  2927. var getPullCmd = (repodef) => {
  2928. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  2929. // console.log(useGitPull)
  2930. var repo = repodef.repo
  2931. var pullCmd = []
  2932. var branch = repodef.branch
  2933. if(!branch) {
  2934. // console.warn('No branch was specified detecting from working client.')
  2935. // First check if working client exists.
  2936. // if (existsSync(instanceroot + '/' + repo)) {
  2937. pullCmd= gitops.getdiscoverbranchcmd(repodef)
  2938. // }
  2939. // else performPullOrClone
  2940. }
  2941. // var pullCmd = ['pullall', [], { cwd : repo }]
  2942. // if (useGitPull) by default... default should probably be pullall i.e. all remotes all branches...
  2943. // var pullCmd = [gitInstallDir
  2944. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  2945. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  2946. if(branch) {
  2947. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2948. var pullCmd = [ gitbash
  2949. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2950. , { cwd: repodef.repodir + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2951. }
  2952. else pullCmd = ['git', ['pull'], {
  2953. inherit: true, shell: true,
  2954. cwd: repodef.repodir + '/' + repo
  2955. // , env: ENV
  2956. , runas: processedArgs.runas
  2957. , title: `git pull ${repo}`
  2958. }]
  2959. return pullCmd
  2960. }
  2961. var getPullOrCloneTask = (repodef, branch, owner, errHandler, elevatedBatch, regularBatch) => {
  2962. // PB : TODO -- Handle no branch passed in case.
  2963. // if(!branch) { throw 'No branch specified' }
  2964. var repo = repodef.repo;
  2965. repodef.repodir = repodef.repodir || instanceroot
  2966. repodef.branch = repodef.branch || branch
  2967. elevatedBatch = elevatedBatch || [];
  2968. regularBatch = regularBatch || [];
  2969. try{
  2970. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  2971. // This remote repo and branch may have been or may need to be added as a local tracking branch
  2972. // to any other local repo folder (with a different name)
  2973. var exists = existsSync(instanceroot + '/' + repo)
  2974. }
  2975. catch(e){
  2976. exists = false
  2977. console.log(e)
  2978. }
  2979. function initTask(etask){
  2980. etask.info = { repo }
  2981. etask.errHandler = errHandler
  2982. etask.statuslog = statuslog
  2983. etask.processedArgs = processedArgs
  2984. etask.selectedinstance = selectedinstance
  2985. etask.runtimestamp = runtimestamp
  2986. etask.ENV = ENV
  2987. }
  2988. function initElevatedBatch(){
  2989. elevatedBatch.info = { repo }
  2990. elevatedBatch.errHandler = errHandler
  2991. elevatedBatch.statuslog = statuslog
  2992. elevatedBatch.processedArgs = processedArgs
  2993. elevatedBatch.selectedinstance = selectedinstance
  2994. elevatedBatch.runtimestamp = runtimestamp
  2995. elevatedBatch.ENV = ENV
  2996. }
  2997. if (exists) {
  2998. var tasks = [];
  2999. return (()=>{
  3000. // PB : TODO -- We need a non cacheable set of properties that need to default to something but then need to escplicitly specified in each run.
  3001. if(selectedinstance.addremotes) {
  3002. return oplist['get-remotes']({repo}).then(( remotes )=>{
  3003. return oplist['get-upstream']({repo, remotes}).then(( upstream ) => {
  3004. return __addremotesandpull({ upstream, remotes})
  3005. })
  3006. })
  3007. }
  3008. else return __pull();
  3009. })()
  3010. function __pull(){
  3011. var branchprint = branch ? ' branch :' + branch : '';
  3012. var task = ()=>{
  3013. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  3014. return any(tasks).then( ()=>{
  3015. return nodeShellExec.apply(null, getPullCmd(repodef)).then(() => {
  3016. return true;
  3017. })
  3018. })
  3019. }
  3020. initTask(task)
  3021. if(repodef.requiresElevation) {
  3022. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3023. if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]) } // PB : TDOO -- Make sure first task also has run context. May need to be moved to win_verse
  3024. else initTask(elevatedBatch[elevatedBatch.length-1])
  3025. return elevatedBatch[elevatedBatch.length-1]
  3026. }
  3027. else {
  3028. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3029. return regularBatch[regularBatch.length-1]
  3030. }
  3031. }
  3032. function __addremotesandpull(options){
  3033. // Add the remotes
  3034. var tasks = []
  3035. // selectedinstance.selectedremotes are optional and need not be enforced to be chosen. The selection for hte selected remotes
  3036. // could also be derived from a crossfilter of remote-type selected for this run and the current chosen and operating reposervers.
  3037. var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
  3038. if(selectedremotes.length > 0) var selectedremoteFilter = function(rs) { return selectedremotes.find( rs.server ) }
  3039. else var selectedremoteFilter = function(){ return true }
  3040. var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
  3041. // We need a most permissive filtered list to use as an efficient starting point to further reduce to whats actually needed.
  3042. // However if such a cached list is not available we need to build it by scaning and apply all the filters anyway on the whole world.
  3043. Object.keys(repoRemotes).forEach((remotename)=>{
  3044. // PB : TODO -- ai prefix for all apis that require an answer amongst many choices.
  3045. var ai_RemoteAddNeeded = (r)=>{
  3046. if(r.server === reposerver && selectedremoteFilter() && r.accessibility.find( selectedinstance[ 'remote-type' ] )){ // currently chosen remotetype...
  3047. var exists = false;
  3048. if(exists = (options.remotes[r.remotename] || Object.keys(options.remotes).find( lrn => {
  3049. var exists = options.remotes[lrn].server === r.server && !options.remotes[r.remotename]
  3050. if(exists) console.warn('Found duplicate remote with a different name for the same server...')
  3051. return exists
  3052. } )) ) {
  3053. return false // Already a remote not required.
  3054. }
  3055. return true // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3056. }
  3057. return false
  3058. };
  3059. tasks.push(
  3060. ()=>{
  3061. return oplist['remote exists']({
  3062. remotename, repo, benign : true, ignorefailures : true
  3063. , url : repoRemotes[remotename].url + repo
  3064. , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3065. }).then( (r) => {
  3066. if(!r[1]) return false; // PB : TODO -- Not accessible skip for now probably should remove.
  3067. else if(r[0]) return true; // Already added nothing to do
  3068. else if(ai_RemoteAddNeeded( repoRemotes[remotename] )) return oplist['remote add']( { remotename,
  3069. 'set-upstream' : (selectedinstance['upstream'] || `${remotename}/${branch}`) // ??? when url accessible... in order of highest priority
  3070. , reponame : repo
  3071. , url : repoRemotes[remotename].url , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3072. })
  3073. // else skipped as remote is not relevant for this repo...
  3074. })
  3075. }
  3076. )
  3077. })
  3078. utils.any(tasks).then(()=>{
  3079. __pull()
  3080. })
  3081. }
  3082. }
  3083. else {
  3084. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  3085. console.log('cloning ' + repo)
  3086. // PB : TODO -- add additional remotes after cloning and pull again...
  3087. var task = ()=>{
  3088. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repodef.owner || owner || defaultowner}/` + repo + '.git'],
  3089. {
  3090. inherit: true, shell: true,
  3091. env: ENV
  3092. , cwd : instanceroot
  3093. , runas: processedArgs.runas
  3094. }).then(() => {
  3095. var task = ()=>{
  3096. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  3097. {
  3098. inherit: true, shell: true,
  3099. env: ENV
  3100. , cwd: instanceroot + '/' + repo
  3101. , runas: processedArgs.runas
  3102. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  3103. })
  3104. }
  3105. initTask(task)
  3106. if(repodef.requiresElevation) {
  3107. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3108. return elevatedBatch[elevatedBatch.length-1]
  3109. }
  3110. else {
  3111. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3112. return regularBatch[regularBatch.length-1]
  3113. }
  3114. })
  3115. }
  3116. initTask(task)
  3117. if(repodef.requiresElevation) {
  3118. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3119. return elevatedBatch[elevatedBatch.length-1]
  3120. }
  3121. else {
  3122. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3123. return regularBatch[regularBatch.length-1]
  3124. }
  3125. }
  3126. }
  3127. var util = require('util');
  3128. var cliname = 'elxr';
  3129. var ver = '1.1';
  3130. var readme = `
  3131. Command syntax examples
  3132. elxr
  3133. Displays help. Same as elxr h
  3134. elxr i
  3135. Runs interactive propmts to help choose installation options.
  3136. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  3137. General command syntax.
  3138. Eg: NODE_ENV=development elxr pull elixir
  3139. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  3140. The specific cmd defines what the value is interpreted as.
  3141. There are several cmds that do not require an {{instancename}} parameter.
  3142. Eg: elxr remote remove origin
  3143. Git operations or passthrough external commands on all repository folders in you working directory.
  3144. Main objectives.
  3145. elxr cli is a wrapper around other shell commands and api based operations.
  3146. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  3147. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  3148. `;
  3149. var help = `
  3150. ${readme}
  3151. # list of commands... please refer dveloper documentation for ${cliname}
  3152. \r\n\t${
  3153. Object.keys(oplist).join('\r\n\t')
  3154. }
  3155. `;
  3156. var elxr = {
  3157. help() {
  3158. return chalk.cyanBright(`
  3159. -------------------------------------------------------------------------------
  3160. *** BBH Elixir ***
  3161. -------------------------------------------------------------------------------
  3162. elxr ${ver}
  3163. A cli tool for chess
  3164. ${help}
  3165. -------------------------------------------------------------------------------
  3166. `)
  3167. }
  3168. , info() {
  3169. return chalk.cyanBright(`
  3170. -------------------------------------------------------------------------------
  3171. *** BBH Elixir ***
  3172. -------------------------------------------------------------------------------
  3173. elxr ${ver}
  3174. A cli tool for chess
  3175. -------------------------------------------------------------------------------
  3176. `)
  3177. }
  3178. , getPullOrCloneTask(args){
  3179. // def can be an instance config
  3180. // Or an object with many repos and elevated repos
  3181. // Or a single repo ( Either Elevated or normal. )
  3182. // USAGE
  3183. // elxr pull elixir origin master
  3184. // elxr pull
  3185. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  3186. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  3187. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  3188. // The branch pipline should feed back to master
  3189. // master -> test -> stage -> release[nnnn] -> production
  3190. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  3191. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  3192. var __args = {
  3193. remotename : args.remotename|| processedArgs._[2]
  3194. , url : args.url || processedArgs._[3]
  3195. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  3196. }
  3197. // var commands = [
  3198. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  3199. // ,
  3200. // ]
  3201. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3202. // var pullCmd = [ gitbash
  3203. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3204. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3205. var def = args || {
  3206. repos : selectedinstance.repos,
  3207. elevated : selectedinstance.elevated
  3208. }
  3209. var elevatedpulltasks = null;
  3210. if(def.repo) {
  3211. // Single repo case.
  3212. if(def.repo.requiresElevation) {
  3213. var t1 = function() {
  3214. return performPullOrClone(def).then(() => {
  3215. return true;
  3216. }).catch((e) => {
  3217. console.error(e)
  3218. }).finally(Traq.finally)
  3219. }
  3220. t1.statuslog = statuslog
  3221. t1.selectedinstance = selectedinstance
  3222. t1.processedArgs = processedArgs
  3223. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  3224. }
  3225. else {
  3226. var t2 = function(){
  3227. return performPullOrClone(def).then(() => {
  3228. console.log('pulled ' + JSON.stringify(def.repo))
  3229. return true;
  3230. }).catch((e) => {
  3231. console.error(e)
  3232. })
  3233. // .finally(Traq.finally)
  3234. }
  3235. t2.statuslog = statuslog
  3236. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  3237. }
  3238. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3239. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  3240. }
  3241. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  3242. console.dir(def)
  3243. console.log('Running exlr pull : ' + path.dirname(__dirname))
  3244. var useGitPull = processedArgs.useGitPull || false;
  3245. if(def.elevated || def.repos) {
  3246. if(def.elevated) def.requiresElevation = true;
  3247. else delete def.requiresElevation;
  3248. }
  3249. else {
  3250. if(def.requiresElevation) def.elevated = [def]
  3251. else def.repos = [def]
  3252. }
  3253. var regularpulltasks = function(){ return Promise.resolve(true) }
  3254. if(def.elevated){
  3255. elevatedpulltasks = function() {
  3256. var eBatch = []
  3257. def.elevated.map((def) => getPullOrCloneTask(def, null, null, null, eBatch))
  3258. if(eBatch.length<1) return Promise.resolve(true);
  3259. eBatch[0].processedArgs = processedArgs
  3260. return shell_verse.runElevatedBatch(eBatch).then(() => {
  3261. return true;
  3262. }).catch((e) => {
  3263. console.error(e)
  3264. })
  3265. }
  3266. elevatedpulltasks.statuslog = statuslog
  3267. }
  3268. if(def.repos) {
  3269. var regularpulltasks = function(){
  3270. var pendingpulls = [];
  3271. def.repos.forEach((def) => {
  3272. pendingpulls.push(
  3273. // PB : TODO serializing to prevent out of memory.
  3274. // Need to optimize as batches and streams...
  3275. function(){
  3276. // if(def.repo === 'setup') return;
  3277. // if(def.repo !== 'chess-client-lib') return;
  3278. return performPullOrClone(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  3279. .catch(e => {
  3280. console.error(util.inspect(e)); throw e })
  3281. }
  3282. )
  3283. })
  3284. return any(pendingpulls).finally(Traq.finally)
  3285. }
  3286. regularpulltasks.statuslog = statuslog
  3287. }
  3288. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3289. // else return getTaskWithoutElevation({ regularpulltasks})
  3290. return elevatedpulltasks().then(()=>{
  3291. if(shell_verse.isWin() && isElevated) return Promise.resolve(true);
  3292. return regularpulltasks()
  3293. })
  3294. }
  3295. }
  3296. // unbound. Bind before using.
  3297. var unbound_interactionpoints = function(selectedinstance){
  3298. var self = this;
  3299. var _interactionpoints = {
  3300. get runchoice() {
  3301. return {
  3302. label :
  3303. `Choose an option :
  3304. d) Install the default chess instance.
  3305. => elxr i chess node_env=development --default
  3306. n) Create your custom new instance interactively
  3307. => elxr i {{instanceName}} node_env={{environment}}
  3308. i) Choose an instance and environment to install
  3309. => elxr i {{instanceName}} node_env={{environment}}
  3310. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3311. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3312. h) Help
  3313. q) Quit
  3314. : `
  3315. , choices : []
  3316. , defaultchoice : 'c'
  3317. , selectedchoice : self.target.runchoice
  3318. , interpret : function(choice){
  3319. var interpret_map = {
  3320. d : function(){
  3321. processedArgs._[0] = 'i'
  3322. self.target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3323. self.target.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3324. self.target.reposerver = 'https://git.bbh.org.in' // PB : TODO -- Read from global defaults...
  3325. }
  3326. , n : function() { processedArgs._[0] = 'i' }
  3327. , i : function() {
  3328. processedArgs._[0] = 'i'
  3329. // processedArgs._[1] = self.target.instanceName || processedArgs._[1] || 'chess';
  3330. }
  3331. , c : async function() {
  3332. // self here will always be the self.target.
  3333. Object.defineProperty(self, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  3334. label : `Enter cmd :
  3335. p) pull
  3336. Default <= p
  3337. : `
  3338. , defaultchoice : 'pull'
  3339. }
  3340. ));
  3341. var cmd = await self.target['cmd'];
  3342. if (!cmd || cmd === 'p') { self.target['cmd'] = processedArgs._[0] = 'pull' }
  3343. else self.target['cmd'] = processedArgs._[0] = cmd
  3344. return cmd;
  3345. }
  3346. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  3347. , q : function() { process.exit() }
  3348. }
  3349. if(Promise.resolve(choice) === choice){
  3350. return choice.then( resolvedchoice => {
  3351. return (interpret_map[choice] || interpret_map['c']).call(self.target)
  3352. })
  3353. }
  3354. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(self.target) )
  3355. // var __interpreter = interpret_map[choice] || interpret_map['c']
  3356. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  3357. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  3358. // return __interpreter.call(self.target)
  3359. }
  3360. }
  3361. }
  3362. , get instanceName() {
  3363. return { label : `Enter Instance Name ( <= ${self.target.instanceName || 'chess'} ) : `
  3364. , choices : self.choices['instanceName'], defaultchoice : 'chess'
  3365. , selectedchoice : self.target.instanceName
  3366. }
  3367. }
  3368. , get instanceType() {
  3369. return { label : `Enter Instance Type ( <= ${self.target.instanceType || 'development'} ) : `
  3370. , choices : self.choices['instanceType'], defaultchoice : 'development'
  3371. , selectedchoice : self.target.instanceType || 'development'
  3372. }
  3373. }
  3374. , get reposerver() {
  3375. return { label : `Enter Repo Server Base Url ( <= ${self.target.reposerver || 'https://git.bbh.org.in'} ) : `
  3376. , get choices() {
  3377. // self.choices['reposerver'].forEach( rs => {
  3378. // var __rs = new URL(rs);
  3379. // __rs.hostname = __rs.host;
  3380. // __rs.path = '/'
  3381. // __rs.method = 'GET'
  3382. // RESTAPI.get(__rs, function(data){ rs.accessibility = 'accessible' }
  3383. // , function(error){ rs.accessibility = 'unaccessible' } )
  3384. // })
  3385. return self.choices['reposerver']
  3386. }
  3387. , set choices(cs) {
  3388. return self.choices['reposerver'].concat([selectedinstance.reposerver]).concat(cs)
  3389. }
  3390. , defaultchoice : selectedinstance.reposerver || 'https://git.bbh.org.in'
  3391. , selectedchoice : self.target.reposerver
  3392. }
  3393. }
  3394. // , 'upstream-remote' : { label : `Enter Remote Name ( <= ${self.target['upstream-remote'] || 'chess'} ) : `
  3395. // , get choices() {
  3396. // var reposerver = self.target['reposerver']
  3397. // var remotes = []
  3398. // var trs = self.target.reposervers || []
  3399. // trs.forEach(rs => {
  3400. // if(rs.server === reposerver){
  3401. // remotes.push(remote)
  3402. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  3403. // }
  3404. // })
  3405. // return remotes
  3406. // }
  3407. // , set choices(addlchoices){
  3408. // var reposerver = self.target['reposerver']
  3409. // var remotes = []
  3410. // var trs = self.target.reposervers || []
  3411. // trs.forEach(rs => {
  3412. // if(rs.server === reposerver){
  3413. // remotes.push(remote)
  3414. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  3415. // }
  3416. // })
  3417. // return remotes.concat(addlchoices)
  3418. // }
  3419. // , defaultchoice : 'userfork'
  3420. // , selectedchoice : self.target['upstream-remote'] || 'userfork'
  3421. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  3422. // }
  3423. // , 'remote-type' : { label : `Enter Remote Type ( <= ${self.target['remote-type'] || 'public'} ) : `
  3424. // , get choices() {
  3425. // return ['external', 'public', 'private', 'github', 'unc']
  3426. // }
  3427. // , set choices(addlchoices){
  3428. // var reposerver = self.target['reposerver']
  3429. // var remotes = []
  3430. // var trs = self.target.reposervers || []
  3431. // trs.forEach(rs => {
  3432. // if(rs.server === reposerver){
  3433. // remotes.push(remote)
  3434. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  3435. // }
  3436. // })
  3437. // return ['external', 'public', 'private', 'github', 'unc'].concat(addlchoices)
  3438. // }
  3439. // , defaultchoice : 'public'
  3440. // , selectedchoice : self.target['remote-type'] || 'public'
  3441. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  3442. // }
  3443. // , 'selectedremotes' : { label : `Chose Remote Names ( <= ${self.target['selectedremotes'] || 'chess'} ) : `
  3444. // , get choices() {
  3445. // var reposerver = self.target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  3446. // var remotenames = []
  3447. // Object.entries(self.target.remotes || []).forEach( ([rname, r]) => {
  3448. // if(r.server === reposerver && r.accessibility.find( self.target[ 'remote-type' ] )){
  3449. // remotes.push(rname)
  3450. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  3451. // }
  3452. // })
  3453. // // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  3454. // // Currenty handles all combinations without any priority order.
  3455. // var _remotechoices = [] // Array of arrays of choices.
  3456. // remotenames.forEach( r => {
  3457. // var __rcs = []
  3458. // _remotechoices.forEach(rc => {
  3459. // __rcs.push( rc.concat(r) )
  3460. // })
  3461. // Array.prototype.push.apply( _remotechoices, __rcs)
  3462. // _remotechoices.push(r)
  3463. // })
  3464. // return _remotechoices
  3465. // }
  3466. // , defaultchoice : ['userfork', 'chess'] // userfork and chess should imlicitly point to userfork-external and chess-external when external connectivity is dtetected.
  3467. // , selectedchoice : self.target['selectedremotes'] || ['userfork-external', 'chess-external']
  3468. // // , defaultchoice : { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  3469. // // , selectedchoice : self.target['selectedremotes'] || { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  3470. // // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  3471. // }
  3472. , get username() { return { label : `Enter User Id for ${self.target.reposerver} ( <= ${self.target.username || 'chess'} ) : `
  3473. , choices : self.choices['username'], defaultchoice : self.target.username || 'chess', selectedchoice : self.target.username } }
  3474. , get password() { return { label : `Enter Password for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.password || ''} ) : `
  3475. , choices : self.choices['password'], defaultchoice : '***', selectedchoice : self.target.password } }
  3476. , get email() { return { label : `Enter Email for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.email || ''} ) : `
  3477. , choices : self.choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : self.target.email } }
  3478. }
  3479. return _interactionpoints
  3480. }
  3481. var get_interactionpoints_template = function(){
  3482. return {
  3483. instanceName : { label : `Enter Instance Name ( <= ${this.target.instanceName || 'chess'} ) : `
  3484. , choices : this.choices['instanceName'], defaultchoice : 'chess'
  3485. , selectedchoice : this.target.instanceName
  3486. }
  3487. }
  3488. }
  3489. var subcommandlabels = {
  3490. switch : (`switch ${processedArgs._[1] || ''}`).trim()
  3491. }
  3492. // The main elxr cli process
  3493. function elxrworker(oplist) {
  3494. var __runcmd = function (label, oplist) {
  3495. var distinquishedlabel = subcommandlabels[label] || label
  3496. return oplist[distinquishedlabel] ? oplist[distinquishedlabel].cmdFn ? oplist[distinquishedlabel].cmdFn(processedArgs) : oplist[distinquishedlabel](processedArgs) : null;
  3497. }
  3498. return __runcmd(processedArgs.label || clioverrides.cmd || processedArgs._[0] || 'undefined', oplist);
  3499. }
  3500. var elxrcmd = (function(){
  3501. var __cmdprototype = function(){}
  3502. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  3503. var __cmd = {
  3504. interpret() {
  3505. var interpreted = {}
  3506. // Non custom command has universal positiona args.
  3507. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  3508. interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  3509. // return clioverrides
  3510. // cmds[cmd] = {
  3511. // interpret() {
  3512. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  3513. // }
  3514. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  3515. // instanceName : true, instanceType : true, reposerver : true } }
  3516. // }
  3517. // ... PB : TODO -- use cmd.toArgs
  3518. interpreted.cmd = this.cmd
  3519. return interpreted
  3520. }
  3521. , getPossiblePrompts(){ return { username : true, password : true, instanceName : true, instanceType : true, reposerver : true } }
  3522. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  3523. , finalized : true
  3524. , toArgs : function( o ){
  3525. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  3526. return o }
  3527. }
  3528. function __createO(o){
  3529. if(o.finalized) return o;
  3530. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  3531. // console.log(subs)
  3532. // console.log(o)
  3533. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  3534. var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  3535. , {}, __cmd, cmds[o.cmd], o)
  3536. cmds[o.cmd] = created;
  3537. created.cmdFn = oplist[o.cmd] || o.cmdFn || created.cmdFn
  3538. oplist[o.cmd] = created.cmdFn;
  3539. noprerequisites[o.cmd] = created.noprerequisites
  3540. return created.cmdFn;
  3541. }
  3542. function create(o){ return __createO(o) }
  3543. __cmdprototype.create = create;
  3544. return __cmdprototype;
  3545. })()
  3546. function resetgitconfig(){
  3547. // https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  3548. // use git config --edit --system to remove the helper = manager line so that it is no longer registered as a credential helper.
  3549. // For bonus points, use git config --edit --global and insert:
  3550. // [core]
  3551. // askpass =
  3552. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  3553. // Git Credential storage...
  3554. // git config --global credential.helper 'store --file ~/.elxrcredentials'
  3555. // git credential fill
  3556. // protocol=https
  3557. // host=git.bbh.org.in
  3558. // username=bob
  3559. // password=pppp
  3560. // git credential-store --file ~/.gitcredentials store
  3561. // // notepad C:/Program Files/Git/etc/gitconfig
  3562. // git config --edit --system
  3563. // git credential-store --file ~/git.store store
  3564. // Find system git config
  3565. // git config --global --edit
  3566. // git config --list --show-origin
  3567. // git config --list --show-origin --show-scope
  3568. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  3569. // Recipie
  3570. // git config --global --unset credentials.helper
  3571. // cd /path/to/my/repo
  3572. // git config --unset credential.helper
  3573. // git config credential.helper 'store --file ~/.git_repo_credentials'
  3574. // git config credential.*.username my_user_name
  3575. // git config credential.https://gitlab.com.username my_user_name
  3576. // git credential fill
  3577. // git config --global credential.modalprompt false // doesnst work.
  3578. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  3579. var options = {
  3580. inherit: true, shell: true, env: ENV
  3581. , cwd: instanceroot
  3582. , runas: processedArgs.runas
  3583. }
  3584. var task = ['git', ['config'], options]
  3585. var tasklist = [
  3586. // ['--global', '--unset credentials.helper']
  3587. // ['--unset', 'credentials.helper']
  3588. // ,
  3589. // ['credential.helper', `'store --file git_repo_credentials'`]
  3590. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  3591. , ['--global', '--replace-all', 'user.name', 'pb']
  3592. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  3593. // , ['--list']
  3594. // , ['credential', 'fill']
  3595. ]
  3596. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  3597. var shellT = (args) => { return getgitbashtask(args, onEachError)
  3598. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  3599. }
  3600. execserial(tasklist, task, shellT, onEachError )
  3601. }
  3602. function reinit(){
  3603. sysAddPathVar('%AppData%\\npm')
  3604. resetgitconfig()
  3605. }
  3606. function init(){
  3607. sysAddPathVar('%AppData%\\npm')
  3608. resetgitconfig()
  3609. }
  3610. const GITSHELL = (function(){
  3611. const GITSHELL = function(){}
  3612. GITSHELL.bash = shell_verse.getbash()
  3613. GITSHELL.getdiscoverbranchcmd = function(repodef){
  3614. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3615. var cmd = [GITSHELL.bash
  3616. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3617. , { cwd: repodef.repodir + '/' + repodef.repo, title: 'discoverbranch for ' + repodef.repo + ' ' + parameters.join(' ') }]
  3618. return cmd
  3619. }
  3620. GITSHELL.getPullCmd = (repodef) => {
  3621. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  3622. // console.log(useGitPull)
  3623. var repo = repodef.repo
  3624. var pullCmd = []
  3625. var branch = repodef.branch
  3626. if(!branch) {
  3627. // console.warn('No branch was specified detecting from working client.')
  3628. // First check if working client exists.
  3629. // if (existsSync(instanceroot + '/' + repo)) {
  3630. pullCmd = GITSHELL.getdiscoverbranchcmd(repodef)
  3631. // }
  3632. // else performPullOrClone
  3633. }
  3634. // var pullCmd = ['pullall', [], { cwd : repo }]
  3635. // if (useGitPull) by default... default should probably be pullall i.e. all remotes all branches...
  3636. // var pullCmd = [gitInstallDir
  3637. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3638. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  3639. if(branch) {
  3640. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3641. var pullCmd = [ gitbash
  3642. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3643. , { cwd: repodef.repodir + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3644. }
  3645. else pullCmd = ['git', ['pull'], {
  3646. inherit: true, shell: true,
  3647. cwd: repodef.repodir + '/' + repo
  3648. // , env: ENV
  3649. , runas: processedArgs.runas
  3650. , title: `git pull ${repo}`
  3651. }]
  3652. return pullCmd
  3653. }
  3654. GITSHELL.pullORcloneSHELLCMD = ( repodef ) => {
  3655. // console.dir(repodef)
  3656. ARGUMENTVALIDATOR.validate( repodef, { repo : true, repodir : true, branch : true })
  3657. var repo = repodef.repo;
  3658. repodef.repodir = repodef.repodir || instanceroot
  3659. var branch = repodef.branch
  3660. var elevatedBatch = repodef.elevatedBatch || [];
  3661. var regularBatch = repodef.regularBatch || [];
  3662. var errorHandler = (e) => {
  3663. console.error(e)
  3664. throw e;
  3665. }
  3666. function initTask(etask){
  3667. etask.info = { repo }
  3668. etask.errHandler = elevatedBatch.errHandler || errorHandler
  3669. etask.statuslog = statuslog
  3670. etask.processedArgs = processedArgs
  3671. etask.selectedinstance = selectedinstance // utils.assign({}, selectedinstance, { root : repodef.repodir })
  3672. etask.runtimestamp = runtimestamp
  3673. etask.ENV = ENV
  3674. }
  3675. function initElevatedBatch(){
  3676. elevatedBatch.info = { repo }
  3677. elevatedBatch.errHandler = elevatedBatch.errHandler || errorHandler
  3678. elevatedBatch.statuslog = statuslog
  3679. elevatedBatch.processedArgs = processedArgs
  3680. elevatedBatch.selectedinstance = selectedinstance //utils.assign({}, selectedinstance, { root : repodef.repodir })
  3681. elevatedBatch.runtimestamp = runtimestamp
  3682. elevatedBatch.ENV = ENV
  3683. }
  3684. try{
  3685. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  3686. // This remote repo and branch may have been or may need to be added as a local tracking branch
  3687. // to any other local repo folder (with a different name) may yet be this repository...
  3688. var exists = existsSync(repodef.repodir + '/' + repo)
  3689. }
  3690. catch(e){
  3691. exists = false
  3692. console.log(e)
  3693. }
  3694. if (exists) {
  3695. var tasks = [];
  3696. return __pull();
  3697. function __pull(){
  3698. var branchprint = branch ? ' branch :' + branch : '';
  3699. var cmd = GITSHELL.getPullCmd(repodef)
  3700. // ['git', ['pull', '-c', 'core.symlinks=true', repodef.remotebase + `/${getowner(repodef)}/` + repo + ( repodef.localrepo ? '' : '.git') ],
  3701. // {
  3702. // inherit: true, shell: true,
  3703. // env: ENV
  3704. // , cwd : repodef.repodir
  3705. // , runas: repodef.requiresElevation || processedArgs.runas
  3706. // }]
  3707. var task = ()=>{
  3708. return any(tasks).then( ()=>{
  3709. console.log('pulling ' + repodef.repodir + '/' + repo + branchprint )
  3710. return nodeShellExec.apply(null, cmd).then(() => {
  3711. return true;
  3712. })
  3713. })
  3714. }
  3715. initTask(task)
  3716. if(repodef.requiresElevation) {
  3717. task.selectedinstance = selectedinstance // { root : repodef.repodir }
  3718. task.args = [cmd[0], [cmd[1].join(' ')], cmd[2]]
  3719. // task.args = GITSHELL.getPullCmd(repodef)
  3720. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3721. if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]) } // PB : TDOO -- Make sure first task also has run context. May need to be moved to win_verse
  3722. else initTask(elevatedBatch[elevatedBatch.length-1])
  3723. return elevatedBatch[elevatedBatch.length-1]
  3724. }
  3725. else {
  3726. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3727. return regularBatch[regularBatch.length-1]
  3728. }
  3729. }
  3730. }
  3731. else {
  3732. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  3733. // PB : TODO -- add additional remotes after cloning and pull again...
  3734. var cmd = ['git', ['clone', '-c', 'core.symlinks=true', repodef.remotebase + `/` + repo + ( repodef.localrepo ? '' : '.git') ],
  3735. {
  3736. inherit: true, shell: true,
  3737. env: ENV
  3738. , cwd : repodef.repodir
  3739. , runas: repodef.requiresElevation || processedArgs.runas
  3740. }]
  3741. var task = ()=>{
  3742. console.log('cloning ' + repo)
  3743. return nodeShellExec.apply( null, cmd).then(() => {
  3744. var task = ()=>{
  3745. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  3746. {
  3747. inherit: true, shell: true,
  3748. env: ENV
  3749. , cwd: repodef.repodir + '/' + repo
  3750. , runas: repodef.requiresElevation || processedArgs.runas
  3751. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  3752. })
  3753. }
  3754. initTask(task)
  3755. if(repodef.requiresElevation) {
  3756. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3757. return elevatedBatch[elevatedBatch.length-1]
  3758. }
  3759. else {
  3760. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3761. return regularBatch[regularBatch.length-1]
  3762. }
  3763. })
  3764. }
  3765. initTask(task)
  3766. if(repodef.requiresElevation) {
  3767. console.dir(cmd)
  3768. task.selectedinstance = selectedinstance // { root : repodef.repodir }
  3769. task.args = [cmd[0], [cmd[1].join(' ')], cmd[2]]
  3770. console.dir(task.args)
  3771. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3772. return elevatedBatch[elevatedBatch.length-1]
  3773. }
  3774. else {
  3775. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3776. return regularBatch[regularBatch.length-1]
  3777. }
  3778. }
  3779. }
  3780. return GITSHELL
  3781. })()
  3782. var cmdFns = {
  3783. resetgitconfig, reinit, init, g : oplist['g'], 'get-upstream' : oplist['get-upstream']
  3784. }
  3785. Object.entries(cmds).forEach( ca => {
  3786. ca[1].cmd = ca[0]
  3787. ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
  3788. ca[1].noprerequisites = noprerequisites[ca[1].cmd]
  3789. elxrcmd.create( ca[1] )
  3790. })
  3791. shell_verse.cmds = cmds;
  3792. shell_verse.generateDependencies()
  3793. console.dir(Object.keys(shell_verse.cmds))
  3794. // ---------------
  3795. Tasq.addlistener(statuslog.statuslog)
  3796. if(clioverrides.noprerequisites) return elxrworker(cmds)
  3797. var pending = (function() {
  3798. // PB : TODO -- Override cli prefs and call with undefined selectedinstance only if there is no cli overide or selection.
  3799. acquirelocalinstances( { root : ENV.wd } )
  3800. function createLocalChessInstance( cfg ){
  3801. // return createInstance(cfg)
  3802. reconfirm = getReconfirmAll()
  3803. var inst = {};
  3804. var __new = Object.assign({}, __default, cfg)
  3805. inst[cfg.node_env] = __new; return inst;
  3806. }
  3807. if(chessinstances.error) {
  3808. delete chessinstances.error
  3809. // use installchoices only when we don't find chessinstances.
  3810. try { var installchoices = require(path.normalize(ENV.wd + '/installchoices.js'))
  3811. var instanceName = installchoices.instanceName;
  3812. var reposerver = installchoices.reposerver
  3813. var node_env = clioverrides.node_env || installchoices.node_env
  3814. var __instance = (chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  3815. instanceName, node_env, root, reposerver /* promptkeys['reposerver'] */ } ))[node_env];
  3816. chessinstances['current_run'] = { instanceName, node_env, reposerver, root }
  3817. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  3818. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  3819. // }
  3820. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  3821. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  3822. __instance.username = installchoices.username = installchoices.gitUser
  3823. __instance.email = installchoices.email = installchoices.gitEmail
  3824. }
  3825. catch(e){
  3826. console.warn(e)
  3827. console.warn( 'Install choices not found. WIll prompt for choices' ) // This is not an error. A new fresh instance is probably being setup.
  3828. throw 'PROMPT FOR INSTLL CHOICES TO BE IMPLEMENTED'
  3829. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  3830. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  3831. }
  3832. }
  3833. // PB : chessinstances.js update if we are switching repo servers, username etc... Myabe always refresh on each run.
  3834. // root location for instance swithc ?? should not be allowd...
  3835. var instanceName = clioverrides.instanceName || chessinstances.current_run.instanceName
  3836. var instance = {}
  3837. function oninstanceName(instanceName) {
  3838. var instance_ = chessinstances[instanceName]
  3839. if(instance_) {
  3840. instance = instance_[clioverrides.node_env || chessinstances.current_run.node_env] || utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  3841. }
  3842. else instance = utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  3843. // PB : TODO We should promt like instanceName create a new one instad of undefined ??
  3844. return instance
  3845. }
  3846. if(!instanceName) {
  3847. var interactionpoints = (function() { return { instanceName : get_interactionpoints_template.bind({target : {}, choices : {}})()['instanceName'] } })()
  3848. var eachPrompt = getBoundEachPrompt(instance, utils.assign({}, interactionpoints), interactionpoints, {})
  3849. var pendingtasks = any( Object.keys(interactionpoints).reduce(eachPrompt, []) ).then(()=>{
  3850. return oninstanceName(instance.instanceName)
  3851. })
  3852. }
  3853. else {
  3854. var pendingtasks = Promise.resolve(oninstanceName(instanceName))
  3855. }
  3856. return pendingtasks.then((instance)=>{
  3857. // PB : TODO -- Embed defaults in the build instead of inlining here...
  3858. // PB : TODO -- All these values instanceName, node_env, username, reposervers should come from instace overridden by a finalized cliovrrides...
  3859. // Also attepmt to load preconfig specially for new chessinstances from ../chess-config/...
  3860. var __repo_manifest_elxr = loadmanifest( instance.root + '/elxr'
  3861. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  3862. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  3863. )
  3864. if(__repo_manifest_elxr.error) console.log(__repo_manifest_elxr.e.message)
  3865. var instance_specific_config_manifest = loadmanifest( instance.root + `/${instance.instanceName}-config-${clioverrides.node_env}`
  3866. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  3867. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  3868. )
  3869. if(instance_specific_config_manifest.error) console.log(instance_specific_config_manifest.e.message)
  3870. delete __repo_manifest_elxr.error
  3871. delete __repo_manifest_elxr.e
  3872. // delete __repo_manifest_elxr.utils
  3873. delete instance_specific_config_manifest.error
  3874. delete instance_specific_config_manifest.e
  3875. // delete instance_specific_config_manifest.utils
  3876. // selectedinstance is not complete until we load in the following order of priority...
  3877. // 1) inline defaults
  3878. // 2) elxr defaults & manifest
  3879. // 3) ../chess-config/... defaults TODO
  3880. // 4) local cached lastrun or cli selected instance from chessinstances
  3881. // 5) instance specific manifest from {{instanceName}}-config-{{node_env}} ( can work with stale or on demand currently pulled updated version )
  3882. // 5.5) runconfig ??? lastrun vs fixed runconfig for repetitive stuff. TODO -- runconfig overrides lastrun...
  3883. // 6) cli overrides from command promnt
  3884. // 7) promted selections and reconfirms.
  3885. var __pvt = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3886. , __default, __repo_manifest_elxr, instance
  3887. , { root : ENV.wd, node_env : ENV.NODE_ENV
  3888. , get instanceName() {
  3889. // FInalize to prevent subsequent overrides...
  3890. return instance.instanceName
  3891. }
  3892. }
  3893. , instance_specific_config_manifest
  3894. , clioverrides
  3895. )
  3896. // console.dir(__pvt)
  3897. // Unmergable server overrides
  3898. Object.keys(instance_specific_config_manifest).forEach( key => {
  3899. __pvt[key] = instance_specific_config_manifest[key]
  3900. })
  3901. var __pub = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, __pvt
  3902. // Finalized immutables.
  3903. // We don't need pub to prevent immutability.
  3904. , { get root(){ return __pvt.root }
  3905. , get node_env(){ return __pvt.node_env }
  3906. , get instanceName() { return __pvt.instanceName }
  3907. , get reposindexed(){
  3908. // PB : TODO -- Implement -- One time gettor and then cached...
  3909. var indexed = {}
  3910. this.repos.forEach(r => { indexed[r.repo] = r })
  3911. this.elevated.forEach(r => { indexed[r.repo] = r })
  3912. Object.defineProperty(this, 'reposindexed', { value: indexed, writable: false });
  3913. return indexed;
  3914. }
  3915. , set root(val){
  3916. throw 'root changes not yet supported'
  3917. // if the root changes while we r invoked from somewhere else... we need to reload everything from that location...
  3918. if(__pvt.root === val){
  3919. return __pvt.root = val
  3920. }
  3921. else __pvt.root
  3922. }
  3923. }
  3924. )
  3925. chessinstances[__pub.instanceName] = chessinstances[__pub.instanceName] || {}
  3926. chessinstances[__pub.instanceName][__pub.instanceType] = __pub
  3927. // PB : TODO initinstances is now obselete relocated here
  3928. // Upgrade old formats..
  3929. if(__pub?.repos && !__pub?.repos[0]?.repo) {
  3930. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3931. __pub.repos = __pub.repos.map(function(repo){ return { repo } })
  3932. }
  3933. if(__pub?.elevated && !__pub?.elevated[0]?.repo) {
  3934. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3935. __pub.elevated = __pub.elevated.map(function(repo){ return { repo } })
  3936. }
  3937. // Config from server always override merges into selection except for the current selection.
  3938. // PB : TODO -- utils.assign Array merges are non-distinct...
  3939. // chessinstances[instanceName][node_env] = selectedinstance;
  3940. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3941. // PB : TODO -- We should probably write the new server config also...
  3942. // PB : TODO -- Attempt first one that is available and online...
  3943. // PB : TODO -- system select may need a reconfirm...
  3944. if(!__pub.reposerver) reconfirm['reposerver'] = true
  3945. __pub.reposerver = __pub.reposerver || __pub.reposervers[0]
  3946. cacheWriteInstanceConfig(chessinstances, __pub.root, __pub )
  3947. Object.defineProperty(__g, 'selectedinstance', {
  3948. get(){ return __pub}
  3949. , set( inst ){
  3950. utils.assign(__pub, inst); return __pub
  3951. }
  3952. })
  3953. return __pub;
  3954. })
  3955. })()
  3956. return pending.then(( selectedinstance)=>{
  3957. selectedinstance.launchscript = __filename
  3958. // PB : TODO -- Maybe create a new instance so we can switch around for different values...
  3959. shell_verse.init({ statuslog, selectedinstance, processedArgs, runtimestamp, ENV })
  3960. Object.keys(oplist).forEach( oper => {
  3961. if(cmds[oper]) return
  3962. cmds[oper] = {}
  3963. // cmds[oper] = {
  3964. // // return a interpreted set of arguments for this cmd run context.
  3965. // interpret() { return { cmd : oper, runchoice : 'c' } }
  3966. // }
  3967. })
  3968. var cmdFns = {
  3969. resetgitconfig, reinit, init, g : oplist['g'], 'get-upstream' : oplist['get-upstream']
  3970. }
  3971. Object.entries(cmds).forEach( ca => {
  3972. ca[1].cmd = ca[0]
  3973. ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
  3974. ca[1].noprerequisites = noprerequisites[ca[1].cmd]
  3975. elxrcmd.create( ca[1] )
  3976. })
  3977. shell_verse.cmds = cmds;
  3978. // Instead of waiting for the root to be establised we start working at the current locatoin and then relocate when root changes.
  3979. runlogjson = `${selectedinstance.root}/.elxr/run-${runtimestamp}/run.log`
  3980. ensureDirectoryExistence(runlogjson)
  3981. fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true})) // Initialize a new log file with "logrotate" for every run
  3982. Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  3983. var chalk = require('chalk')
  3984. const homedir = require('os').homedir();
  3985. function sysAddPathVar(addpath){
  3986. // Object.assign({
  3987. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  3988. // }, options)
  3989. // powershell $env:Path -split ';'
  3990. var etask = ()=>{
  3991. return nodeShellExec('Powershell.exe', [
  3992. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  3993. $newpath = $path + ';${addpath}'
  3994. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  3995. ]).then(() => {
  3996. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  3997. }).catch(() => {
  3998. fs.writeFileSync('run.done', 'error')
  3999. })
  4000. }
  4001. etask.statuslog = statuslog
  4002. etask.selectedinstance = selectedinstance
  4003. etask.processedArgs = processedArgs
  4004. etask.runtimestamp = runtimestamp
  4005. etask.ENV = ENV
  4006. return shell_verse.runElevated(etask)
  4007. // var newpath = addpath.split(';');
  4008. // newpath.push(addpath)
  4009. // newpath = Array.from(new Set(newpath)).join(';')
  4010. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  4011. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  4012. // // %AppData%\npm
  4013. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  4014. }
  4015. // singleton one time lazy
  4016. var getCredentials = function(){
  4017. // try {
  4018. // First call
  4019. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  4020. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  4021. console.log(creds);
  4022. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  4023. // }
  4024. // catch(e){
  4025. // console.warn('Credentials not cached. You will be prompted for username and password.')
  4026. // }
  4027. // Subsequent calls
  4028. getCredentials = ()=>{ return creds }
  4029. return getCredentials();
  4030. }
  4031. // console.dir(processedArgs)
  4032. // PB : TODO -- defaults for valuless arguments if passed.
  4033. // Object.keys(processedArgs).forEach(a=>{
  4034. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  4035. // }
  4036. // })
  4037. const { readdir } = require("fs").promises
  4038. // Directory shallow walk and do perform on each dir.
  4039. const dirs = async (perform, src, target, options) => {
  4040. var rs = []
  4041. for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
  4042. if (dir.isDirectory()) rs.push( perform(dir, src, target, options) )
  4043. }
  4044. return any(rs)
  4045. }
  4046. var fsMove = async function(from, to, options) {
  4047. if(!options?.innernode) {
  4048. var exists = fs.existsSync(from);
  4049. var stats = exists && fs.statSync(from);
  4050. var isDirectory = exists && stats.isDirectory();
  4051. }
  4052. else {
  4053. var isDirectory = options.innernode.isDirectory()
  4054. }
  4055. if(!isDirectory) return fs.renameSync(from, to)
  4056. fs.mkdirSync(to, { recursive : true })
  4057. var rs = [];
  4058. for (const innernode of await readdir(from, { withFileTypes: true })) {
  4059. rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) )
  4060. }
  4061. return any(rs)
  4062. };
  4063. // PB : TODO -- Should return a bunch of promises to wait for...
  4064. var copyrecursive = async function(src, target, options) {
  4065. if(!options?.innernode) {
  4066. var exists = fs.existsSync(src);
  4067. var stats = exists && fs.statSync(src);
  4068. var isDirectory = exists && stats.isDirectory();
  4069. }
  4070. else {
  4071. var isDirectory = options.innernode.isDirectory()
  4072. }
  4073. if(!isDirectory) return fs.copyFileSync(src, target)
  4074. fs.mkdirSync(target, { recursive : true })
  4075. var rs = [];
  4076. for (const innernode of await readdir(src, { withFileTypes: true })) {
  4077. rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
  4078. // .then(()=>{
  4079. // return any(actions.map( a => ()=>a(dir, { isDirectory : true}) ))
  4080. // })
  4081. )
  4082. }
  4083. return any(rs)
  4084. // return fswalk( src, {}, [
  4085. // (src, options)=> {
  4086. // if(options.innernode.isDirectory()) fs.mkdirSync(options.target, { recursive : true })
  4087. // else fs.copyFileSync(src, options.target)
  4088. // }
  4089. // ])
  4090. // var exists = fs.existsSync(src);
  4091. // var stats = exists && fs.statSync(src);
  4092. // var isDirectory = exists && stats.isDirectory();
  4093. // if (isDirectory) {
  4094. // fs.mkdirSync(dest, { recursive : true });
  4095. // return dirs( function(childItemName) {
  4096. // return copyrecursive(path.join(src, childItemName.name),
  4097. // path.join(dest, childItemName.name));
  4098. // }, src )
  4099. // } else {
  4100. // fs.copyFileSync(src, dest);
  4101. // }
  4102. };
  4103. // var renamerecursive = function(from, to){
  4104. // var exists = fs.existsSync(from);
  4105. // var stats = exists && fs.statSync(from);
  4106. // var isDirectory = exists && stats.isDirectory();
  4107. // if (isDirectory) {
  4108. // fs.mkdirSync(to);
  4109. // dirs( function(childItemName) {
  4110. // renamerecursive(path.join(from, childItemName),
  4111. // path.join(to, childItemName));
  4112. // }, from )
  4113. // // fs.readdirSync(from).forEach(function(childItemName) {
  4114. // // copyrecursive(path.join(from, childItemName),
  4115. // // path.join(to, childItemName));
  4116. // // });
  4117. // } else {
  4118. // fsrename(from, to);
  4119. // }
  4120. // }
  4121. // filesystem walk
  4122. const fswalk = async (pathToWalk, options, actions) => {
  4123. // options = options || { depthfirst : true }
  4124. if(!options.innernode) {
  4125. var exists = fs.existsSync(pathToWalk);
  4126. var stats = exists && fs.statSync(pathToWalk);
  4127. var isDirectory = exists && stats.isDirectory();
  4128. }
  4129. else {
  4130. var isDirectory = options.innernode.isDirectory()
  4131. }
  4132. if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  4133. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
  4134. var rs = [];
  4135. for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
  4136. rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
  4137. // .then(()=>{
  4138. // return any(actions.map( a => ()=>a(innernode, { isDirectory : true}) ))
  4139. // })
  4140. )
  4141. }
  4142. // Wait for the walk to complete before renaming directories.
  4143. Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  4144. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ))
  4145. return any(rs)
  4146. }
  4147. var fsrecurse = function(target, options, actions, root) {
  4148. var exists = fs.existsSync(target);
  4149. var stats = exists && fs.statSync(target);
  4150. var isDirectory = exists && stats.isDirectory();
  4151. if (isDirectory) {
  4152. var tasks = []
  4153. tasks.push( dirs( function(childItemName) {
  4154. return fsrecurse(path.join(target, childItemName.name)
  4155. , options, actions, root);
  4156. }, target ))
  4157. return any(tasks)
  4158. } else {
  4159. var prevActionResult = null;
  4160. return any( actions.map( (action) => prevActionResult = action.apply(null, target, options) ))
  4161. }
  4162. };
  4163. // var fslink = function(to, options){ try { fs.linkSync( to, options.from ) } catch(e) { throw e } }
  4164. var fslink = function(to, options){ fs.symlinkSync( to, options.from /*, type = "junction"*/ ) }
  4165. var fsrename = function(target, options){
  4166. // PB : TODO -- streaming and async.. target could be a stream a string or a filesystem item or a tree node...
  4167. var targetname = options.innernode?.name || path.parse(target).base;
  4168. var replaced = targetname;
  4169. options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ) })
  4170. if(replaced && replaced !== targetname) {
  4171. var tr = target.replace( targetname, replaced )
  4172. fs.renameSync(target, tr)
  4173. return tr;
  4174. }
  4175. else return replaced
  4176. }
  4177. var fscontentreplace = function( target, options ){
  4178. // do many replacements in one shot in the file.
  4179. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
  4180. var content = fs.readFileSync(target, { encoding: 'utf8' }) // PB : TODO -- streaming and async..
  4181. options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ) })
  4182. fs.writeFileSync(target, content)
  4183. }
  4184. }
  4185. var templatelink = function(target, options){
  4186. var targetSubPath = target.replace(options.workingtarget + '/', '' );
  4187. var targetSubPathsplit = targetSubPath.split("/")
  4188. var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`
  4189. var linkToSubPathReplacement = `${options.base}-server-lib/common`
  4190. // var rgxp = new RegExp(`(__link__)${options.base}-server-lib`, "g")
  4191. var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g")
  4192. var linkToSubPath = targetSubPath
  4193. var b = target.match(rgxp)
  4194. var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } )
  4195. linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot)
  4196. if( b ) {
  4197. // Only if the pattern matches which is link instruction.
  4198. linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } )
  4199. }
  4200. options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ) })
  4201. var linkToName = `${options.destinationroot}/${linkToSubPath}`
  4202. if(b){
  4203. linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement)
  4204. // PB : DONT DELETE EVERYTHING ??? Only the linkable ones... Or use an add strategy without deleting...
  4205. fs.unlinkSync( target );
  4206. fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } )
  4207. }
  4208. else {
  4209. fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName )
  4210. // fsMove( `${options.workingtarget}/${linkToSubPath}`, linkFromName )
  4211. }
  4212. }
  4213. // Source and Target are files or folders. We need another version or a unifed version for strings..
  4214. var processpatterns = function(target, options){
  4215. // Accept a set of patterns and substitutions and operate on a target and apply all patterns substitutions.
  4216. // options = options || { targettype : 'inplace', sourcetype : 'filesystem' }
  4217. // options.source, options.target sourcetype = 'string' | 'filesystem' options.targettype = 'inplace' | 'copy'
  4218. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' ) {
  4219. options.patternsubstitutions.forEach( ps => {
  4220. // var replacement = regexreplaceall( from, ps.strOrregexp, ps.substitutes )
  4221. // if(targetname) { // Porcess all files. Even if file names dont have patterns the content needs to be replaced.
  4222. return options.tasks.map( t => { return t( target, ps ) } )
  4223. // }
  4224. // return str.replace(regex, function(match, key) {
  4225. // console.log(`Found match, group ${match}: ${key}`);
  4226. // return substitutes[key] || match;
  4227. // })
  4228. })
  4229. }
  4230. // while ((m = regex.exec(str)) !== null) {
  4231. // // This is necessary to avoid infinite loops with zero-width matches
  4232. // if (m.index === regex.lastIndex) {
  4233. // regex.lastIndex++;
  4234. // }
  4235. // var rstr = str;
  4236. // // The result can be accessed through the `m`-variable.
  4237. // m.forEach((match, groupIndex) => {
  4238. // // rstr = rstr.replace( groupIndex
  4239. // console.log(`Found match, group ${groupIndex}: ${match}`);
  4240. // if(groupIndex === 0) return
  4241. // });
  4242. // }
  4243. }
  4244. function copyFileSync( source, target , options) {
  4245. var targetFile = target;
  4246. // If target is a directory, a new file with the same name will be created
  4247. if ( fs.existsSync( target ) ) {
  4248. if ( fs.lstatSync( target ).isDirectory() ) {
  4249. targetFile = path.join( target, path.basename( source ) );
  4250. }
  4251. }
  4252. fs.writeFileSync(targetFile, fs.readFileSync(source));
  4253. }
  4254. function copyFolderRecursiveSync( source, target, options ) {
  4255. var files = [];
  4256. // Check if folder needs to be created or integrated
  4257. var targetfolder = path.join( target, path.basename( source ) );
  4258. if ( !fs.existsSync( targetfolder ) ) {
  4259. fs.mkdirSync( targetfolder );
  4260. }
  4261. // Copy
  4262. if ( fs.lstatSync( source ).isDirectory() ) {
  4263. files = fs.readdirSync( source );
  4264. files.forEach( function ( file ) {
  4265. var curSource = path.join( source, file );
  4266. if ( fs.lstatSync( curSource ).isDirectory() ) {
  4267. copyFolderRecursiveSync( curSource, targetfolder );
  4268. } else {
  4269. copyFileSync( curSource, targetfolder );
  4270. }
  4271. } );
  4272. }
  4273. }
  4274. var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }}
  4275. var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) }
  4276. var getTaskCheckExists = shell_verse.getTaskCheckExists
  4277. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  4278. // var getTaskWithoutElevation = function(tasdef){
  4279. // return ()=>{
  4280. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  4281. // else Promise.resolve(true)
  4282. // }
  4283. // }
  4284. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  4285. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  4286. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  4287. var dbForLabel = function (label) {
  4288. var dbsForLabel = {
  4289. devmysql: 'mysql'
  4290. , development: 'mssql'
  4291. , production: 'mssql'
  4292. }
  4293. return dbsForLabel[label] || 'mysql'
  4294. }
  4295. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  4296. // Relevant git repos
  4297. var useGitPull = processedArgs.useGitPull || false;
  4298. var configPromise = null
  4299. var reconfirmcmds = { create : true }
  4300. var independentcmd = function(){
  4301. return false;
  4302. }
  4303. function preworkerconfig(){
  4304. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  4305. gitRepos = selectedinstance.repos
  4306. // gitRepos = ['chess-server-lib'];
  4307. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  4308. elevatedRunasRepos = selectedinstance.elevated
  4309. // Repos that should excluded from merge for releases...
  4310. exludeMergeRepos = selectedinstance.exludeMergeRepos
  4311. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  4312. // mysql -u root -p db_name < drop_all_tables.sql
  4313. var mysql = '../xampp/mysql/bin/mysql'
  4314. var mysqldump = '../xampp/mysql/bin/mysqldump'
  4315. }
  4316. // function acquireChoices(selectedinstance) {
  4317. // var hasconfig = false;
  4318. // console.warn(chalk.cyan(`
  4319. // -------------------------------------------------------------------------------
  4320. // Could not locate your preferred configuration (you may not specified it)
  4321. // You should fork the default chess configuration to customize and make it
  4322. // your own instance with a named config as
  4323. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  4324. // And then run this tool as follows
  4325. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  4326. // OR
  4327. // Run this tool with the following command to use a quick start default.
  4328. // elxr --default
  4329. // OR
  4330. // Choose one of the options below to run interactively.
  4331. // We will run your choice at the next prompt.
  4332. // -------------------------------------------------------------------------------
  4333. // `))
  4334. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  4335. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  4336. // return initinstances(selectedinstance)
  4337. // })
  4338. // // var prompt = cli.prompter;
  4339. // // return prompt.ask(`Choose an option :
  4340. // // d) Install the default chess instance.
  4341. // // => elxr i chess node_env=development --default
  4342. // // n) Create your custom new instance interactively
  4343. // // => elxr i {{instanceName}} node_env={{environment}}
  4344. // // i) Choose an instance and environment to install
  4345. // // => elxr i {{instanceName}} node_env={{environment}}
  4346. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  4347. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  4348. // // h) Help
  4349. // // q) Quit
  4350. // // Default <= d
  4351. // // : `).then((choice) => {
  4352. // // if (choice && choice === 'd' || !choice) {
  4353. // // processedArgs._[0] = 'i'
  4354. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  4355. // // selectedinstance.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  4356. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  4357. // // }
  4358. // // else if (choice === 'h') {
  4359. // // processedArgs._[0] = 'h'
  4360. // // fs.writeFileSync('run.done', 'noop help');
  4361. // // console.log(elxr.help()); process.exit()
  4362. // // }
  4363. // // else if (choice === 'n' || choice === 'i') {
  4364. // // var p1 = cli.prompter;
  4365. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  4366. // // processedArgs._[0] = 'i'
  4367. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  4368. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  4369. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  4370. // // if (choice === 'n') {
  4371. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  4372. // // console.warn(
  4373. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  4374. // // process.exit();
  4375. // // }
  4376. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  4377. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  4378. // // })
  4379. // // })
  4380. // // })
  4381. // // } else if (choice === 'c') {
  4382. // // var p1 = cli.prompter;
  4383. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  4384. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  4385. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  4386. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  4387. // // return p1.ask(`Enter cmd :
  4388. // // p) pull
  4389. // // Default <= p
  4390. // // : `).then(function (cmd) {
  4391. // // if (!cmd || cmd === 'p') {
  4392. // // processedArgs._[0] = 'pull'
  4393. // // }
  4394. // // else processedArgs._[0] = cmd
  4395. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  4396. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  4397. // // })
  4398. // // })
  4399. // // })
  4400. // // })
  4401. // // } else {
  4402. // // 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.`));
  4403. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  4404. // // fs.writeFileSync('run.done', 'noop quit');
  4405. // // process.exit()
  4406. // // }
  4407. // // })
  4408. // }
  4409. var os = require("os");
  4410. var hostname = os.hostname();
  4411. var clustername = null; // PB : TODO -- Prompt to acquire.
  4412. var configs = (function(){
  4413. // We need to discover and use the most specialized config available.
  4414. // Two passes are required as the config currently cloned may be switched by the discovery.
  4415. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  4416. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  4417. return {
  4418. ownerClusterNodeConfig(selected) {
  4419. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  4420. // Also many cluster node instance can be running as a set of services on the same host on the same port with ( specific domain names )
  4421. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  4422. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  4423. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  4424. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  4425. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  4426. e.benign = true
  4427. return e; }
  4428. )
  4429. }
  4430. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  4431. , selected.instanceName + '-config-' + selected.node_env
  4432. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  4433. e.benign = true
  4434. return e }
  4435. )
  4436. }
  4437. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  4438. , commonInstance(selected) { return __acquireConfig(selected, { owner : defaultowner }
  4439. , undefined
  4440. , function(e){
  4441. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  4442. statuslog.statuslog(e, e)
  4443. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  4444. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  4445. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4446. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  4447. console.dir(selectedinstance.repos)
  4448. // Config from server always override merges into selection except for the current selection.
  4449. // PB : TODO -- utils.assign Array merges are non-distinct...
  4450. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  4451. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4452. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4453. }
  4454. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  4455. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4456. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4457. }
  4458. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4459. , selected, selectedinstance)
  4460. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  4461. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4462. cacheWriteInstanceConfig(chessinstances, selectedinstance.root, selectedinstance)
  4463. // ENV.NODE_ENV = selectedinstance.node_env;
  4464. throw e
  4465. }
  4466. ) }
  4467. // , genericChessInstance(selected) { return __acquireConfig(selected, { owner : defaultowner }) }
  4468. }
  4469. })()
  4470. var eNotImplemented = function(){
  4471. console.error('Not yet implemented')
  4472. process.exit()
  4473. }
  4474. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  4475. var acquireConfig = function(slections){
  4476. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  4477. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  4478. return acquireData(slections)
  4479. })
  4480. }
  4481. var instanceData = (function(){
  4482. return {
  4483. ownerClusterNodeData(selected) {
  4484. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  4485. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  4486. return __acquireData(selected, { remote : 'userfork' }
  4487. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  4488. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  4489. e.benign = true
  4490. return e; }
  4491. )
  4492. }
  4493. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  4494. , selected.instanceName + '-data-' + selected.node_env
  4495. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  4496. e.benign = true
  4497. return e }
  4498. )
  4499. }
  4500. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  4501. , commonInstance(selected) { return __acquireData(selected, { owner : defaultowner }
  4502. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  4503. ) }
  4504. , genericChessInstance(selected) { return __acquireData(selected, { owner : defaultowner }) }
  4505. }
  4506. })()
  4507. var acquireData = function(slections){
  4508. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  4509. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  4510. }
  4511. var createTasq = (args, shellT, onEachError) => {
  4512. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  4513. tasq.toString = function(){ return JSON.stringify(args)}
  4514. return tasq;
  4515. }
  4516. var execserial = function(tasklist, task, shellT){
  4517. var exec = (taskArgs)=>{
  4518. var thistask = task.concat();
  4519. thistask[1] = thistask[1].concat()
  4520. thistask[1].push.apply(thistask[1], taskArgs)
  4521. return createTasq(thistask, shellT)
  4522. }
  4523. return any(tasklist.map(exec))
  4524. }
  4525. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  4526. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  4527. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  4528. var owner = options.owner || selected.username || options.defaultowner // getowner(repodef, remote) //
  4529. var errorHandler = (e) => {
  4530. 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`))){
  4531. // console.error('Could not connect to repo server. Timed Out')
  4532. 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 => {
  4533. if(propValue === 'y') {
  4534. reconfirm = getReconfirmAll()
  4535. return startElxr()
  4536. }
  4537. else if(propValue === 'r'){
  4538. return acquireConfig(selected)
  4539. }
  4540. else process.exit()
  4541. })
  4542. }
  4543. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  4544. var choices = {
  4545. t : `install a new temporary local instance with this name ( will not persist ).
  4546. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  4547. , e : 'exit' }
  4548. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  4549. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4550. , {
  4551. i : 'create a new instance with this name => will fork the default config under your username'
  4552. , f : 'fork a new instance with this name for yourself for this node from another instance'
  4553. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  4554. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  4555. , p : 'create a custom config for yourself '
  4556. }, choices)
  4557. }
  4558. return cli.prompt( choices
  4559. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  4560. if(propValue === 't') {
  4561. selectedinstance.local = true; return createInstance(selectedinstance)
  4562. }
  4563. if(propValue === 'i') return eNotImplemented()
  4564. if(propValue === 'f') return eNotImplemented()
  4565. if(propValue === 'o') return eNotImplemented()
  4566. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4567. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4568. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4569. else process.exit()
  4570. })
  4571. }
  4572. console.warn(e)
  4573. throw e; //('Config acquisition failed.')
  4574. }
  4575. var successHandler = () => {
  4576. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  4577. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  4578. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4579. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }))
  4580. console.dir(selectedinstance.repos)
  4581. // Config from server always override merges into selection except for the current selection.
  4582. // PB : TODO -- utils.assign Array merges are non-distinct...
  4583. if(!selectedinstance.repos[0].repo) {
  4584. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4585. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4586. }
  4587. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  4588. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4589. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4590. }
  4591. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4592. , selected, selectedinstance)
  4593. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  4594. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4595. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4596. ENV.NODE_ENV = selectedinstance.node_env;
  4597. }
  4598. return performPullOrClone( selected.reposindexed[configrepo] || { repo : configrepo }
  4599. , null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4600. .catch( (e)=>{
  4601. // if(e){
  4602. if(Promise.resolve(e) === e) return e;
  4603. // console.error(e)
  4604. e.benign = true;
  4605. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  4606. // }
  4607. })
  4608. }
  4609. var __acquireData = function (selected, options, datarepo, errHandler) {
  4610. datarepo = datarepo || selected.instanceName + '-data';
  4611. var owner = options.owner || selected.username || options.defaultowner //getowner(repodef, remote) //
  4612. var errorHandler = (e) => {
  4613. 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`))){
  4614. // console.error('Could not connect to repo server. Timed Out')
  4615. 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 => {
  4616. if(propValue === 'y') {
  4617. reconfirm = getReconfirmAll()
  4618. return startElxr()
  4619. }
  4620. else if(propValue === 'r'){
  4621. return acquireConfig(selected)
  4622. }
  4623. else process.exit()
  4624. })
  4625. }
  4626. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
  4627. var choices = {
  4628. t : `install a temporary local data folder.
  4629. For more options. Request and use a personal username at chess@bbh.org.in )`
  4630. , e : 'exit' }
  4631. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  4632. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4633. , {
  4634. i : 'create a new instance with this name => will fork the default config under your username'
  4635. , f : 'fork a new instance with this name for yourself for this node from another instance'
  4636. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  4637. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  4638. , p : 'create a custom config for yourself '
  4639. }, choices)
  4640. }
  4641. return cli.prompt( choices
  4642. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  4643. if(propValue === 't') {
  4644. selectedinstance.local = true; return createInstanceData(selectedinstance)
  4645. }
  4646. if(propValue === 'i') return eNotImplemented()
  4647. if(propValue === 'f') return eNotImplemented()
  4648. if(propValue === 'o') return eNotImplemented()
  4649. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4650. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4651. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4652. else process.exit()
  4653. })
  4654. }
  4655. console.warn(e)
  4656. throw e; //('Config acquisition failed.')
  4657. }
  4658. var successHandler = () => {
  4659. }
  4660. return performPullOrClone( selected.reposindexed[datarepo] || { repo : datarepo }
  4661. , null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4662. .catch( (e)=>{
  4663. // if(e){
  4664. if(Promise.resolve(e) === e) return e;
  4665. // console.error(e)
  4666. e.benign = true;
  4667. throw e; // Not a hard error but we need this for bcontinueonfailure
  4668. // }
  4669. })
  4670. }
  4671. // ----------------------------------------------------------------
  4672. // PB : TODO -- Review and obsolete...
  4673. // ----------------------------------------------------------------
  4674. // var launchpath = path.resolve(path.normalize(ENV.wd))
  4675. var launchpath = selectedinstance.root
  4676. // // we were run.
  4677. // // The easisest would be to ask for a target directory and default to current dir....
  4678. // // path.dirname(launchpath).split(path.sep).pop()
  4679. // var parent = path.dirname(launchpath);
  4680. // var pp = launchpath;
  4681. // var instancediscoverytasks = [];
  4682. // while(parent !== pp){
  4683. // instancediscoverytasks.push(
  4684. // ((pa)=>{
  4685. // var p = pa;
  4686. // return function(){
  4687. // return hasElxr(p).then((value)=>{
  4688. // if(value) return p
  4689. // // PB : TODO -- Using throw like this is not friendly with any...
  4690. // throw Object.assign( new Error('Benign Failure in Batch')
  4691. // , { value : false, benign : true });
  4692. // })
  4693. // }
  4694. // })(pp)
  4695. // )
  4696. // pp = parent;
  4697. // parent = path.dirname(parent);
  4698. // }
  4699. // var instanceroot = null
  4700. // var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  4701. // if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  4702. // else instanceroot = ir.pVal
  4703. // return instanceroot
  4704. // }).catch(()=>{
  4705. // instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  4706. // })
  4707. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  4708. // Then acquire and reload and replace this default.
  4709. var __interactive_prompts = function( target, choices, promptsfilter ){
  4710. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  4711. var interactionpoints = unbound_interactionpoints.bind({target, choices})(selectedinstance)
  4712. function getPromptKeys() {
  4713. // PB : TODO -- get interactionpoints
  4714. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  4715. return promptkeys // PB : TODO __ Convert pormptkeys to filtered interactionpoints.
  4716. }
  4717. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  4718. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  4719. }
  4720. var downloadsdir = shell_verse.downloadsdir;
  4721. var prerequisites = [
  4722. {
  4723. shellcmd: 'git',
  4724. name : 'git',
  4725. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  4726. , installer: 'Git-2.31.0-64-bit.exe'
  4727. , installcmd: ['cmd', ['/c', 'start',
  4728. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  4729. , '/VERYSILENT'
  4730. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  4731. ]]
  4732. , preinstallsteps: function() {
  4733. var steps = [
  4734. () => {
  4735. if (!existsSync(downloadsdir + '/' + this.installer)) {
  4736. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  4737. }
  4738. else return Promise.resolve(true)
  4739. }
  4740. ]
  4741. var prompts = this.getuser(null, ()=>{
  4742. // console.log('preinstallsteps')
  4743. // var gitUser = 'guest';
  4744. // var gitEmail = 'guest@bbh.org.in';
  4745. // var prompts = [];
  4746. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  4747. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  4748. // console.log('prompting in preinstallsteps')
  4749. // return any(prompts).then(()=>{
  4750. // var steps = [
  4751. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  4752. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  4753. // ]
  4754. // return any(steps.map(getshelltask)).then(() => {
  4755. // })
  4756. // });
  4757. return Promise.resolve(true)
  4758. })
  4759. return any([any(steps), prompts])
  4760. }
  4761. , installsteps: function () {
  4762. return any([this.installcmd].map(getshelltask))
  4763. }
  4764. , postinstallsteps: function(err, users){
  4765. return this.getuser(null, (err, data)=>{
  4766. // ignore err and proceed with data as guest.
  4767. console.dir(data)
  4768. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  4769. return username = data[0];
  4770. }
  4771. data = data || ['guest']
  4772. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4773. console.log('prompting in postinstallsteps')
  4774. var username = 'guest';
  4775. var email = 'guest@bbh.org.in';
  4776. var password = '***';
  4777. return any( getInteractionPoints([selectedinstance], promptkeys, { username, password, email}) ).then(()=>{
  4778. if(!data.find(e => e === selectedinstance.username)) {
  4779. var steps = [
  4780. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  4781. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  4782. ]
  4783. return any(steps.map(getshelltask)).then(() => {
  4784. })
  4785. }
  4786. else {
  4787. return Promise.resolve(true)
  4788. }
  4789. });
  4790. })
  4791. }
  4792. , install: function () {
  4793. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  4794. }
  4795. , verifyAndInstall : function(){
  4796. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  4797. if(exists) {
  4798. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  4799. return this.postinstallsteps.bind(this)()
  4800. }
  4801. return this.install();
  4802. });
  4803. }
  4804. , getuser : function(repo, onResult){
  4805. var __onResult = onResult || function(e, data){
  4806. data = data || []
  4807. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4808. // console.dir(choices)
  4809. return data[0]
  4810. }
  4811. var globalOrLocal = '--global';
  4812. if(repo) globalOrLocal = '--local'
  4813. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  4814. // not yet configured.
  4815. if(!result.success) return __onResult(result)
  4816. else {
  4817. var users = result.messages[0].trim().split('\n');
  4818. if(users.length === 0 ||
  4819. users.length === 1 && users[0] === 'guest') {
  4820. return __onResult(result)
  4821. }
  4822. else {
  4823. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  4824. }
  4825. })
  4826. .catch((e)=>{
  4827. console.error(e)
  4828. return __onResult(e)
  4829. })
  4830. }
  4831. }
  4832. ,
  4833. {
  4834. shellcmd: 'node',
  4835. name : 'node',
  4836. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  4837. , installer: 'node-v14.16.0-x64.msi'
  4838. , installcmd: ['MSIEXEC.exe', ['/i'
  4839. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  4840. , 'ACCEPT=YES', '/passive']]
  4841. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  4842. }
  4843. ]
  4844. for(var i=0; i<prerequisites.length; i++) {
  4845. prerequisites[prerequisites[i].name] = prerequisites[i];
  4846. }
  4847. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  4848. var mainTasks = [];
  4849. function verifyAndInstallPrerequisites() {
  4850. var downloadtasks = [];
  4851. var installtasks = [];
  4852. prerequisites.forEach(preq => {
  4853. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  4854. if (exists) console.log(`${preq.shellcmd} exists`)
  4855. else {
  4856. console.log(`${preq.shellcmd} is not installed`)
  4857. return preq.preinstallsteps.call(preq).then(() => {
  4858. installtasks.push(preq.install.bind(preq))
  4859. })
  4860. }
  4861. }))
  4862. })
  4863. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  4864. }
  4865. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  4866. var promptkeys = {
  4867. cmd : processedArgs._[0] || 'pull'
  4868. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  4869. // 'instanceName' : true
  4870. // , 'node_env' : true
  4871. // , username : ''
  4872. // , runchoice : 'c'
  4873. }
  4874. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  4875. var choices = {
  4876. 'instanceName' : []
  4877. , 'reposerver' : []
  4878. , 'upstream-remote' : []
  4879. , 'instanceType' : []
  4880. , username : ['guest', 'chessdemo', 'demo']
  4881. }
  4882. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  4883. var instances = []
  4884. var reposervers = [];
  4885. var remotes = [];
  4886. var instanceNames = []
  4887. var instanceTypes = ['development', 'production'];
  4888. // Accumulate all known choices from every possible instance...
  4889. Object.keys( chessinstances).forEach(instanceName => {
  4890. if(instanceName === 'current_run') return ;
  4891. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  4892. var instance = chessinstances[instanceName][node_env];
  4893. reposervers = reposervers.concat(instance.reposervers)
  4894. if(instance.reposerver) reposervers.push(instance.reposerver)
  4895. instances.push(instance)
  4896. instanceTypes.push(instance.node_env)
  4897. instanceNames.push(instance.instanceName)
  4898. var otherremotes = instance?.reposerverinstances
  4899. if(otherremotes) otherremotes = otherremotes[instance?.reposerver]?.remotes
  4900. otherremotes = otherremotes || {}
  4901. Array.prototype.push.apply(remotes, Object.keys(otherremotes))
  4902. })
  4903. })
  4904. instances = instances.concat(detectedinstanceoptions)
  4905. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  4906. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  4907. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  4908. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  4909. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  4910. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  4911. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  4912. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  4913. }
  4914. var detection_state = {
  4915. localInstanceDetected : false
  4916. }
  4917. function createInstanceData(target, source) {
  4918. var sourceinstance = source || target;
  4919. console.dir(sourceinstance)
  4920. var args = {
  4921. remotebase : sourceinstance.reposerver
  4922. , sourcerepo : sourceinstance.repo || 'chess-data'
  4923. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4924. }
  4925. if(sourceinstance.local) {
  4926. var options = {
  4927. inherit: true, shell: true,
  4928. env: ENV
  4929. , cwd : instanceroot
  4930. , runas: processedArgs.runas
  4931. }
  4932. var cmdseq = [
  4933. ['git', ['clone', `${args.remotebase}/${owner}/${args.sourcerepo}`, `${args.targetrepo}`], options]
  4934. ]
  4935. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4936. }
  4937. else {
  4938. // http://try.gitea.io/api/v1/org/{org}/repos
  4939. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4940. throw 'createInstanceData is possible only within the same repository server.'
  4941. }
  4942. var server = new URL(target.reposerver);
  4943. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4944. , username : target.username, password : target.password
  4945. }
  4946. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4947. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4948. return GITEA.repository.updateattributes( {
  4949. hostname : server.host, protocol : server.protocol
  4950. , username : target.username, password : target.password
  4951. }
  4952. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4953. , { name : `${args.targetrepo}`}
  4954. )
  4955. }
  4956. )
  4957. }
  4958. // GITEA.repository.updateattributes( {
  4959. // hostname : server.host, protocol : server.protocol
  4960. // , username : selectedinstance.username, password : selectedinstance.password
  4961. // }
  4962. // , { repo : `chess-config`, owner : selectedinstance.username }
  4963. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4964. // )
  4965. // return selectedinstance
  4966. }
  4967. function createInstance(target, source) {
  4968. var sourceinstance = source || target;
  4969. console.dir(sourceinstance)
  4970. var args = {
  4971. remotebase : sourceinstance.reposerver + '/chess/'
  4972. , sourcerepo : sourceinstance.repo || 'chess-config'
  4973. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4974. }
  4975. if(sourceinstance.local) {
  4976. var options = {
  4977. inherit: true, shell: true,
  4978. env: ENV
  4979. , cwd : instanceroot
  4980. , runas: processedArgs.runas
  4981. }
  4982. var cmdseq = [
  4983. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4984. ]
  4985. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4986. }
  4987. else {
  4988. // http://try.gitea.io/api/v1/org/{org}/repos
  4989. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4990. throw 'createInstance is possible only within the same repository server.'
  4991. }
  4992. var server = new URL(target.reposerver);
  4993. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4994. , username : target.username, password : target.password
  4995. }
  4996. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4997. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4998. return GITEA.repository.updateattributes( {
  4999. hostname : server.host, protocol : server.protocol
  5000. , username : target.username, password : target.password
  5001. }
  5002. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  5003. , { name : `${args.targetrepo}`}
  5004. )
  5005. }
  5006. )
  5007. }
  5008. // GITEA.repository.updateattributes( {
  5009. // hostname : server.host, protocol : server.protocol
  5010. // , username : selectedinstance.username, password : selectedinstance.password
  5011. // }
  5012. // , { repo : `chess-config`, owner : selectedinstance.username }
  5013. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  5014. // )
  5015. // return selectedinstance
  5016. }
  5017. var skipprerequisites = false;
  5018. function initinstances() {
  5019. // var root = selectedinstance.root
  5020. var instanceName = selectedinstance.instanceName
  5021. var node_env = selectedinstance.node_env
  5022. var reposerver = selectedinstance.reposerver
  5023. // var instanceName = selectedinstance.instanceName
  5024. // || clioverrides.instanceName
  5025. // // || processedArgs._[1]
  5026. // || chessinstances.current_run.instanceName
  5027. // var node_env = selectedinstance.node_env
  5028. // || clioverrides.node_env
  5029. // // || processedArgs.node_env
  5030. // || chessinstances.current_run.node_env
  5031. // var reposerver = selectedinstance.reposerver
  5032. // || clioverrides.reposerver
  5033. // // || processedArgs.node_env
  5034. // || chessinstances.current_run.reposerver
  5035. // if(!instanceName) {
  5036. // promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  5037. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  5038. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  5039. // }
  5040. // if(!node_env) {
  5041. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  5042. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  5043. // }
  5044. // if(!reposerver) {
  5045. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  5046. // }
  5047. // chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  5048. // instanceName, node_env, root : selectedinstance.root, reposerver : selectedinstance.reposerver /* promptkeys['reposerver'] */ } );
  5049. // chessinstances['current_run'] = { instanceName: selectedinstance.instanceName, node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver, root }
  5050. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  5051. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  5052. // }
  5053. // Override sequence.
  5054. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  5055. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  5056. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  5057. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  5058. if(selectedinstance.node_env === undefined) delete selectedinstance.node_env
  5059. // selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  5060. // , __default
  5061. // , chessinstances[instanceName][node_env]
  5062. // , clioverrides
  5063. // , selectedinstance
  5064. // // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  5065. // );
  5066. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  5067. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  5068. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  5069. // // Brand New.
  5070. // selectedinstance = Object.assign( __default, selectedinstance )
  5071. // }
  5072. // Upgrade old formats..
  5073. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  5074. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  5075. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  5076. }
  5077. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  5078. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  5079. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  5080. }
  5081. // Config from server always override merges into selection except for the current selection.
  5082. // PB : TODO -- utils.assign Array merges are non-distinct...
  5083. // chessinstances[instanceName][node_env] = selectedinstance;
  5084. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  5085. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  5086. // PB : TODO -- We should probably write the new server config also...
  5087. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  5088. return chessinstances
  5089. }
  5090. var skipprereqs = {}
  5091. var maintask = () => {
  5092. // Default cmd to run !
  5093. processedArgs._[0] === processedArgs._[0] || 'pull';
  5094. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  5095. if(!noprerequisites[processedArgs._[0]]
  5096. && !skipprereqs[processedArgs._[0]]
  5097. ) {
  5098. return prerequisites.git.verifyAndInstall().then(()=>{
  5099. var e = { message : 'verifyAndInstall', success : true}
  5100. var inittasks = []
  5101. var commontask = () => { preworkerconfig(); return elxrworker(oplist) }
  5102. if(!detection_state.localInstanceDetected) {
  5103. var t1 = ()=>{ return createInstance(selectedinstance) };
  5104. t1.statuslog = statuslog
  5105. var specifictask = shell_verse.getNonElevatedTask(t1)
  5106. }
  5107. else {
  5108. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  5109. t2.statuslog = statuslog
  5110. var specifictask = shell_verse.getNonElevatedTask(t2)
  5111. }
  5112. inittasks.push( specifictask().catch((err) => {
  5113. e = err;
  5114. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  5115. console.error(err)
  5116. }).then( commontask )
  5117. // .finally(()=>{
  5118. // fs.writeFileSync('run.lfog', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  5119. // if(!e.success) fs.writeFileSync('run.done', 'error');
  5120. // // return process.exit()
  5121. // }))
  5122. )
  5123. return any(inittasks)
  5124. })
  5125. }
  5126. else {
  5127. console.log('cmd has no preqs or has been configured to skip preqs')
  5128. preworkerconfig()
  5129. return elxrworker(oplist)
  5130. }
  5131. }
  5132. function generateDependencies(){ return shell_verse.generateDependencies() }
  5133. var startElxr = function() {
  5134. const retaincount = 2
  5135. var min = runtimestamp;
  5136. var collect = []
  5137. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  5138. reconfirm = getReconfirmAll()
  5139. }
  5140. // detectedinstanceoptions.splice(0,0, __default) // PB : TODO -- Merge multiple...
  5141. var detectedinstanceoptions = [selectedinstance]
  5142. var cmdinstance = cmds[clioverrides.cmd]
  5143. var cmdprompts = cmdinstance.getPossiblePrompts()
  5144. // selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  5145. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  5146. utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, selectedinstance, promptkeys )
  5147. // promptkeys = utils.assign(promptkeys, clioverrides)
  5148. // startElxr requires instance // Independent cmds should have already been bypassed.
  5149. // if(cmdprompts.instanceName) {
  5150. // not an instanceless cmd.
  5151. // console.dir(selectedinstance)
  5152. try {
  5153. // chessinstances = acquirelocalinstances(selectedinstance);
  5154. // findlocalinstances(chessinstances, detectedinstanceoptions)
  5155. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  5156. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  5157. var inst = initinstances(selectedinstance)
  5158. detection_state.localInstanceDetected = true;
  5159. return inst;
  5160. })
  5161. }
  5162. catch (e) {
  5163. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  5164. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  5165. return initinstances(selectedinstance)
  5166. })
  5167. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  5168. // // Weve not been told what to do.
  5169. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  5170. // }
  5171. todo = todo.then(() => {
  5172. try {
  5173. // chessinstances = acquirelocalinstances(selectedinstance)
  5174. // findlocalinstances(chessinstances, detectedinstanceoptions)
  5175. // detectedinstanceoptions.splice(0,0, __default)
  5176. initinstances(selectedinstance)
  5177. detection_state.localInstanceDetected = true;
  5178. }
  5179. catch (e) {
  5180. // console.error(e)
  5181. console.log('No local instances config found in current root = ' + selectedinstance.root);
  5182. console.log('A config will be createed with the instance and environment chosen...')
  5183. // return (async ()=>{return await __default.reposerver})().then(()=>{
  5184. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  5185. // return selectedinstance = Object.assign(__default, selectedinstance);
  5186. // })
  5187. detection_state.localInstanceDetected = false;
  5188. return selectedinstance
  5189. }
  5190. })
  5191. }
  5192. return todo.then( ()=>{
  5193. // PB : TODO -- Embed this in the build instead of inlining it.
  5194. // PB : TODO -- Also attepmt to load from ../chess-config/... as base for new instances...
  5195. initinstances(selectedinstance) // PB : TODO Review Initinstancess... and cleanup
  5196. // ---------------------------
  5197. runconfig = { NODE_ENV: selectedinstance.node_env }
  5198. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  5199. generateDependencies();
  5200. if(noprerequisites[processedArgs._[0]]
  5201. || skipprereqs[processedArgs._[0]]
  5202. ) {
  5203. return elxrworker(oplist)
  5204. }
  5205. var neTask = ()=>{
  5206. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  5207. // collect garbage
  5208. return dirs( (dir)=>{
  5209. var matches = /run-(.*)/gm.exec(dir.name)
  5210. if(matches) {
  5211. if(+(matches[1]) < min) {
  5212. min = matches[1]
  5213. collect.splice( 0, 0, matches[1] )
  5214. }
  5215. else collect.push(matches[1])
  5216. }
  5217. return Promise.resolve(collect);
  5218. }, `${selectedinstance.root}/.elxr` )
  5219. .then(()=>{
  5220. // delete garbage
  5221. if(collect.length > retaincount) {
  5222. var asyncs = [];
  5223. while((collect.length - asyncs.length) > retaincount) {
  5224. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  5225. }
  5226. return Promise.all(asyncs)
  5227. }
  5228. else return true
  5229. })
  5230. .catch(e => {
  5231. console.error
  5232. })
  5233. }
  5234. neTask.statuslog = statuslog
  5235. shell_verse.getNonElevatedTask( neTask )()
  5236. var commonTask = ()=>{
  5237. verifyAndInstallPrerequisites.statuslog = statuslog
  5238. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  5239. mainTasks.push(maintask)
  5240. return any(mainTasks);
  5241. }
  5242. return commonTask()
  5243. })
  5244. // }
  5245. // else return Promise.resolve(true)
  5246. }
  5247. // return detectInstanceRoot.then(()=>{
  5248. var cmdobj = cmds[selectedinstance.cmd]
  5249. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  5250. if(cmdobj.independentcmd) {
  5251. if(cmdobj.requiresElevation) {
  5252. return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  5253. }
  5254. else return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  5255. }
  5256. else return startElxr()
  5257. })
  5258. .catch(e => {
  5259. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  5260. else console.log('error : ' + e)
  5261. })
  5262. // })
  5263. })
  5264. })
  5265. // .then( () => {
  5266. // console.log(process._getActiveHandles());
  5267. // console.log(process._getActiveRequests());
  5268. // })
  5269. // detect if alread installed -> Take no action.
  5270. // download if no installer avalable -> next()
  5271. // install
  5272. function checkandinstall(items) {
  5273. var tasks = []
  5274. items.forEach(item => {
  5275. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  5276. })
  5277. return Promise.all(tasks).then(existances => {
  5278. existances.forEach((exists, i) => {
  5279. if (!exists) {
  5280. return downloadandinstall([items[i]])
  5281. }
  5282. })
  5283. })
  5284. }
  5285. function downloadandinstall(items) {
  5286. var tasks = []
  5287. items.forEach(item => {
  5288. tasks.push(getTaskDownload(item))
  5289. })
  5290. return Promise.all(tasks)
  5291. }
  5292. // Sample instances config.
  5293. // var instances = {
  5294. // "elixir": {
  5295. // "production": {
  5296. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  5297. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  5298. // , "exludeMergeRepos": {
  5299. // "elixir-config-development": true, "elixir-config-test": true
  5300. // , "elixir-config-production": true, "elixir-data": true
  5301. // }
  5302. // , "instanceName": "elixir", "node_env": "production"
  5303. // }
  5304. // },
  5305. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  5306. // }
  5307. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...