Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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