diff --git a/LICENSE b/LICENSE index e1a278e..cd41e27 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2018, Dan Ryan +Copyright (c) 2018, Dan Ryan and Tzu-ping Chung Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above diff --git a/Pipfile b/Pipfile index 25ed7ee..51464ab 100644 --- a/Pipfile +++ b/Pipfile @@ -1,5 +1,5 @@ [packages] -passa = { editable = true, path = '.' } +passa = { editable = true, path = '.', extras = ['virtualenv'] } [dev-packages] black = '*' diff --git a/Pipfile.lock b/Pipfile.lock index ff1f65c..662eeb7 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "ff353680e286436d85c9b1b00ccb7ee257cb2922a1eec0becf9713817605d92b" + "sha256": "994d50f9fd0acc91cf216cf0ffc1233ebbfd0a411b57320f44a0f4487943e546" }, "pipfile-spec": 6, "requires": {}, @@ -19,16 +19,22 @@ "sha256:9e5896d1372858f8dd3344faf4e5014d21849c756c8d5701f78f8a103b372d92", "sha256:d8b24664561d0d34ddfaec54636d502d7cea6e29c3eaf68f3df6180863e2166e" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '3.6'", + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '3.6'", "version": "==1.4.3" }, "attrs": { "hashes": [ - "sha256:4b90b09eeeb9b88c35bc642cbac057e45a5fd85367b985bd2809c62b7b939265", - "sha256:e0d0eb91441a3b53dab4d9b743eafc1ac44476296a2053b6ca3af0b139faf87b" + "sha256:10cbf6e27dbce8c30807caf056c8eb50917e0eaafe86347671b57254006c3e69", + "sha256:ca4be454458f9dec299268d472aaa5a11f67a4ff70093396e1ceae9c76cf4bbb" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '3.6'", - "version": "==18.1.0" + "version": "==18.2.0" + }, + "backports-functools-lru-cache": { + "hashes": [ + "sha256:f0b0e4eba956de51238e17573b7087e852dfe9854afd2e9c873f73fc0ca0a6dd" + ], + "markers": "python_version <= '2.7' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==1.5" }, "backports-shutil-get-terminal-size": { "hashes": [ @@ -44,6 +50,14 @@ "markers": "python_version < '3.3' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.0.post1" }, + "cached-property": { + "hashes": [ + "sha256:3a026f1a54135677e7da5ce819b0c690f156f37976f3e30c5430740725203d7f", + "sha256:9217a59f14a5682da7c4b8829deadbfc194ac22e9908ccf7c8820234e80a1504" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==1.5.1" + }, "cerberus": { "hashes": [ "sha256:f5c2e048fb15ecb3c088d192164316093fcfa602a74b3386eefb2983aa7e800a" @@ -56,7 +70,6 @@ "sha256:376690d6f16d32f9d1fe8932551d80b23e9d393a8578c5633a2ed39a64861638", "sha256:456048c7e371c089d0a77a5212fb37a2c2dce1e24146e3b7e0261736aaeaa22a" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2018.8.24" }, "chardet": { @@ -64,14 +77,13 @@ "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==3.0.4" }, "distlib": { "hashes": [ "sha256:cd502c66fc27c535bab62dc4f482e403e2369c2c05281a79cc2d4e2f42a87f20" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.2.7" }, "enum34": { @@ -89,7 +101,7 @@ "sha256:3bb3de3582cb27071cfb514f00ed784dc444b7f96dc21e140de65fe00585c95e", "sha256:41d5b64e70507d0c3ca742d68010a76060eea8a3d863e9b5130ab11a4a91aa0e" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.0.1" }, "idna": { @@ -97,7 +109,6 @@ "sha256:156a6814fb5ac1fc6850fb002e0852d56c0c8d2531923a51032d1b70760e186e", "sha256:684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.7" }, "importlib": { @@ -107,6 +118,14 @@ "markers": "python_version < '2.7' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.0.4" }, + "installer": { + "hashes": [ + "sha256:4ad3f14753d506d9ce646ac10320a2b82395208109f2356ed9e7a234976d3b4b", + "sha256:b849d2d876ef71162cfa6fc92204120a5cd215cad373b83fddcab401490d5fbc" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.1.0" + }, "modutil": { "hashes": [ "sha256:2c85c1666649e92e56de17c00e1e831313602d9b55e8661d39c01e39003b45f7", @@ -115,33 +134,34 @@ "markers": "python_version >= '2.6' and python_version >= '3.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.0.0" }, - "more-itertools": { + "mork": { "hashes": [ - "sha256:c187a73da93e7a8acc0001572aebc7e3c69daf7bf6881a2cea10650bd4420092", - "sha256:c476b5d3a34e12d40130bc2f935028b5f636df8f372dc2c1c01dc19681b2039e", - "sha256:fcbfeaea0be121980e15bc97b3817b5202ca73d0eae185b4550cbfce2a3ebb3d" + "sha256:988dd3d768369e9c88bdade3d9b90ed3bfc91cb5eb229a0da4db9b119b0a5d7a", + "sha256:9cf945de7f69ed7ace8062509c5613c9484bdc2a5ac14caed6bba71f31f459c5" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==4.3.0" + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.1.0" }, - "ordereddict": { + "packagebuilder": { "hashes": [ - "sha256:1c35b4ac206cef2d24816c89f89cf289dd3d38cf7c449bb3fab7bf6d43f01b1f" + "sha256:1e85c4e0e994322996b93cd6685c12834d30f3558889154f8e3de8fb1f3fd1e7", + "sha256:dc525d06ecd102db23ab421b879d7d27021d784ff933e33e8c411a53af5c9dbe" ], - "markers": "python_version < '3.0' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==1.1" + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.1.0" }, "packaging": { "hashes": [ "sha256:e9215d2d2535d3ae866c3d6efc77d5b24a0192cce0ff20e42896cc0664f889c0", "sha256:f019b770dd64e585a99714f1fd5e01c7a8f11b45635aa953fd41c689a657375b" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==17.1" }, "passa": { "editable": true, - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "extras": [ + "virtualenv" + ], "path": "." }, "pathlib2": { @@ -149,7 +169,7 @@ "sha256:8eb170f8d0d61825e09a95b38be068299ddeda82f35e96c3301a8a5e7604cb83", "sha256:d1aa2a11ba7b8f7b21ab852b1fb5afb277e1bb99d5dfc663380b5015c0d80c5a" ], - "markers": "python_version < '3.6' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version < '3.5' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.3.2" }, "pip-shims": { @@ -173,35 +193,41 @@ }, "pyparsing": { "hashes": [ - "sha256:0832bcf47acd283788593e7a0f542407bd9550a55a8a8435214a1960e04bcb04", - "sha256:fee43f17a9c4087e7ed1605bd6df994c6173c1e977d7ade7b651292fab2bd010" + "sha256:905d8090c335314568b5faee0025b1829f27bb974604a5762a6cdef3a7dfc3b7", + "sha256:f493ee323be1e94929416b3585eefcc04943115cecbaaa35a8c86d1a2368af19" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==2.2.0" + "version": "==2.2.1" + }, + "recursive-monkey-patch": { + "hashes": [ + "sha256:546739fea5be2ea9f98b5ec44fafeb697b5cf9fdcda64a03422582ab03ee24c4", + "sha256:98922554e77f2e2c85a4f5d873a0f52efdc1b553f32444bd6c788b2ff583bf3e" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.4.0" }, "requests": { "hashes": [ "sha256:63b52e3c866428a224f97cab011de738c36aec0185aa91cfacd418b5d58911d1", "sha256:ec22d826a36ed72a7358ff3fe56cbd4ba69dd7a6718ffd450ff0e9df7a47ce6a" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.19.1" }, "requirementslib": { "hashes": [ - "sha256:7288ec80fa62b78c6193eca85882605c4cdbb60361fc62478bd4a913c0b54400", - "sha256:8bb1b156d8b13337eab359273605b036d60735b350019addabb054e8a89a96f6" + "sha256:90151d8963f814e17190e067b60e92fb35fd1bc46c99f8dba3d7b0d93a3dd958", + "sha256:c3aeaa4e0b80843ba65a68878293e07ea52a8d0706dbba86b02dad6cd20ef2dd" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==1.1.5" + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==1.1.6" }, "resolvelib": { "hashes": [ - "sha256:d52f2c0762deeb2a4cc34a84371a7a5ac85e111bdc69ce9ae729d8d636606ad6", - "sha256:eb759d43bbf50de9bf36afb9f6c269fabf9ff49084dbfad4ba67252d134bf4b5" + "sha256:6c4c6690b0bdd78bcc002e1a5d1b6abbde58c694a6ea1838f165b20d2c943db7", + "sha256:8734e53271ef98f38a2c99324d5e7905bc00c97dc3fc5bb7d83c82a979e71c04" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==0.2.1" + "version": "==0.2.2" }, "scandir": { "hashes": [ @@ -217,7 +243,7 @@ "sha256:c9009c527929f6e25604aec39b0a43c3f831d2947d89d6caaab22f057b7055c8", "sha256:f5c71e29b4e2af7ccdc03a020c626ede51da471173b4a6ad1e904f2b2e04b4bd" ], - "markers": "python_version < '3.5' and python_version < '3.6' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5' and python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version < '3.5' and python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.9.0" }, "six": { @@ -225,7 +251,6 @@ "sha256:70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9", "sha256:832dc0e10feb1aa2c68dcc57dbb658f1c7e65b9b61af69048abc87a2db00a0eb" ], - "markers": "python_version < '3.6' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.11.0" }, "toml": { @@ -237,11 +262,11 @@ }, "tomlkit": { "hashes": [ - "sha256:618b057b96b488bb858102bdb38dd9d451c0617667031e320efea2392a39bec4", - "sha256:6856b5395f7c509baad1911aa3940b3c2fb33f53aff968ed1596c393ccea98e5" + "sha256:8ab16e93162fc44d3ad83d2aa29a7140b8f7d996ae1790a73b9a7aed6fb504ac", + "sha256:ca181cee7aee805d455628f7c94eb8ae814763769a93e69157f250fe4ebe1926" ], "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==0.4.3" + "version": "==0.4.4" }, "typing": { "hashes": [ @@ -249,7 +274,7 @@ "sha256:57dcf675a99b74d64dacf6fba08fb17cf7e3d5fdff53d4a30ea2a5e7e52543d4", "sha256:a4c8473ce11a65999c8f59cb093e70686b6c84c98df58c1dae9b3b196089858a" ], - "markers": "python_version < '3.5' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "(python_version >= '2.7' and python_version < '2.8') or (python_version >= '3.4' and python_version < '3.5') and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5'", "version": "==3.6.6" }, "urllib3": { @@ -257,9 +282,16 @@ "sha256:a68ac5e15e76e7e5dd2b8f94007233e01effe3e50e8daddf69acfd81cb686baf", "sha256:b5725a0bd4ba422ab0e66e89e030c806576753ea3ee08554382c14e685d117b5" ], - "markers": "python_version < '4' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.23" }, + "virtualenv": { + "hashes": [ + "sha256:2ce32cd126117ce2c539f0134eb89de91a8413a29baac49cbab3eb50e2026669", + "sha256:ca07b4c0b54e14a91af9f34d0919790b016923d157afda5efdde55c96718f752" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==16.0.0" + }, "vistir": { "extras": [ "spinner" @@ -276,8 +308,15 @@ "sha256:0a2e54558a0628f2145d2fc822137e322412115173e8a2ddbe1c9024338ae83c", "sha256:80044e51ec5bbf6c894ba0bc48d26a8c20a9ba629f4ca19ea26ecfcf87685f5f" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.31.1" + }, + "yaspin": { + "hashes": [ + "sha256:36fdccc5e0637b5baa8892fe2c3d927782df7d504e9020f40eb2c1502518aa5a", + "sha256:8e52bf8079a48e2a53f3dfeec9e04addb900c101d1591c85df69cf677d3237e7" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.14.0" } }, "develop": { @@ -286,7 +325,6 @@ "sha256:674bb3bab080f598371f4443c5008cbfeb1a5e622dd312395d2d82af2c54c456", "sha256:b63b1f4dc77c074d386752ec4a8a7517600f6c0db8cd42980cae17ab7b3275d7" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.7.11" }, "apipkg": { @@ -302,7 +340,7 @@ "sha256:9e5896d1372858f8dd3344faf4e5014d21849c756c8d5701f78f8a103b372d92", "sha256:d8b24664561d0d34ddfaec54636d502d7cea6e29c3eaf68f3df6180863e2166e" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '3.6'", + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '3.6'", "version": "==1.4.3" }, "argparse": { @@ -310,7 +348,6 @@ "sha256:62b089a55be1d8949cd2bc7e0df0bddb9e028faefc8c32038cc84862aefdd6e4", "sha256:c31647edb69fd3d465a847ea3157d37bed1f95f19760b11a47aa91c04b666314" ], - "markers": "python_version == '2.6'", "version": "==1.4.0" }, "arpeggio": { @@ -318,7 +355,6 @@ "sha256:a5258b84f76661d558492fa87e42db634df143685a0e51802d59cae7daad8732", "sha256:dc5c0541e7cc2c6033dc0338133436abfac53655624784736e9bc8bd35e56583" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.9.0" }, "atomicwrites": { @@ -331,20 +367,25 @@ }, "attrs": { "hashes": [ - "sha256:4b90b09eeeb9b88c35bc642cbac057e45a5fd85367b985bd2809c62b7b939265", - "sha256:e0d0eb91441a3b53dab4d9b743eafc1ac44476296a2053b6ca3af0b139faf87b" + "sha256:10cbf6e27dbce8c30807caf056c8eb50917e0eaafe86347671b57254006c3e69", + "sha256:ca4be454458f9dec299268d472aaa5a11f67a4ff70093396e1ceae9c76cf4bbb" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '3.6'", - "version": "==18.1.0" + "version": "==18.2.0" }, "babel": { "hashes": [ "sha256:6778d85147d5d85345c14a26aada5e478ab04e39b078b0745ee6870c2b5cf669", "sha256:8cba50f48c529ca3fa18cf81fa9403be176d374ac4d60738b839122dfaaa3d23" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.6.0" }, + "backports-functools-lru-cache": { + "hashes": [ + "sha256:f0b0e4eba956de51238e17573b7087e852dfe9854afd2e9c873f73fc0ca0a6dd" + ], + "markers": "python_version <= '2.7' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==1.5" + }, "backports-shutil-get-terminal-size": { "hashes": [ "sha256:0975ba55054c15e346944b38956a4c9cbee9009391e41b86c68990effb8c1f64" @@ -367,6 +408,14 @@ "markers": "python_version >= '3.6'", "version": "==18.6b4" }, + "cached-property": { + "hashes": [ + "sha256:3a026f1a54135677e7da5ce819b0c690f156f37976f3e30c5430740725203d7f", + "sha256:9217a59f14a5682da7c4b8829deadbfc194ac22e9908ccf7c8820234e80a1504" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==1.5.1" + }, "cerberus": { "hashes": [ "sha256:f5c2e048fb15ecb3c088d192164316093fcfa602a74b3386eefb2983aa7e800a" @@ -379,7 +428,6 @@ "sha256:376690d6f16d32f9d1fe8932551d80b23e9d393a8578c5633a2ed39a64861638", "sha256:456048c7e371c089d0a77a5212fb37a2c2dce1e24146e3b7e0261736aaeaa22a" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2018.8.24" }, "chardet": { @@ -387,7 +435,6 @@ "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==3.0.4" }, "click": { @@ -402,7 +449,7 @@ "sha256:463f8483208e921368c9f306094eb6f725c6ca42b0f97e313cb5d5512459feda", "sha256:48eb22f4f8461b1df5734a074b57042430fb06e1d61bd1e11b078c0fe6d7a1f1" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' and sys_platform == 'win32'", + "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' and sys_platform == 'win32' or sys_platform == 'win32'", "version": "==0.3.9" }, "coverage": { @@ -446,7 +493,7 @@ "hashes": [ "sha256:cd502c66fc27c535bab62dc4f482e403e2369c2c05281a79cc2d4e2f42a87f20" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.2.7" }, "docutils": { @@ -455,7 +502,6 @@ "sha256:51e64ef2ebfb29cae1faa133b3710143496eca21c530f3f71424d77687764274", "sha256:7a4bd47eaf6596e1295ecb11361139febe29b084a87bf005bf899f9a42edc3c6" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.14" }, "enum34": { @@ -481,7 +527,7 @@ "sha256:3bb3de3582cb27071cfb514f00ed784dc444b7f96dc21e140de65fe00585c95e", "sha256:41d5b64e70507d0c3ca742d68010a76060eea8a3d863e9b5130ab11a4a91aa0e" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.0.1" }, "funcsigs": { @@ -497,16 +543,14 @@ "sha256:156a6814fb5ac1fc6850fb002e0852d56c0c8d2531923a51032d1b70760e186e", "sha256:684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.7" }, "imagesize": { "hashes": [ - "sha256:3620cc0cadba3f7475f9940d22431fc4d407269f1be59ec9b8edcca26440cf18", - "sha256:5b326e4678b6925158ccc66a9fa3122b6106d7c876ee32d7de6ce59385b96315" + "sha256:3f349de3eb99145973fefb7dbe38554414e5c30abd0c8e4b970a7c9d09f3a1d8", + "sha256:f3832918bc3c66617f92e35f5d70729187676313caa60c187eb0f28b8fe5e3b5" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==1.0.0" + "version": "==1.1.0" }, "importlib": { "hashes": [ @@ -522,13 +566,21 @@ ], "version": "==17.5.0" }, + "installer": { + "hashes": [ + "sha256:4ad3f14753d506d9ce646ac10320a2b82395208109f2356ed9e7a234976d3b4b", + "sha256:b849d2d876ef71162cfa6fc92204120a5cd215cad373b83fddcab401490d5fbc" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.1.0" + }, "invoke": { "hashes": [ - "sha256:1c2cf54c9b9af973ad9704d8ba81b225117cab612568cacbfb3fc42958cc20a9", - "sha256:334495ea16e73948894e9535019f87a88a44b73e7977492b12c2d1b5085f8197", - "sha256:54bdd3fd0245abd1185e05359fd2e4f26be0657cfe7d7bb1bed735e054fa53ab" + "sha256:4f4de934b15c2276caa4fbc5a3b8a61c0eb0b234f2be1780d2b793321995c2d6", + "sha256:dc492f8f17a0746e92081aec3f86ae0b4750bf41607ea2ad87e5a7b5705121b7", + "sha256:eb6f9262d4d25b40330fb21d1e99bf0f85011ccc3526980f8a3eaedd4b43892e" ], - "version": "==1.1.1" + "version": "==1.2.0" }, "jinja2": { "hashes": [ @@ -567,12 +619,19 @@ "markers": "python_version < '3.0' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.1" }, + "packagebuilder": { + "hashes": [ + "sha256:1e85c4e0e994322996b93cd6685c12834d30f3558889154f8e3de8fb1f3fd1e7", + "sha256:dc525d06ecd102db23ab421b879d7d27021d784ff933e33e8c411a53af5c9dbe" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.1.0" + }, "packaging": { "hashes": [ "sha256:e9215d2d2535d3ae866c3d6efc77d5b24a0192cce0ff20e42896cc0664f889c0", "sha256:f019b770dd64e585a99714f1fd5e01c7a8f11b45635aa953fd41c689a657375b" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==17.1" }, "parver": { @@ -580,7 +639,6 @@ "sha256:ac4afff688d19d5e1876bb68d4bccc1a1b6a5cc8bd6a646939a14d366695ba15", "sha256:f025fba8f88a9c776971df6d62b6cf7f37d1108f84c163bda91e157d7d527075" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.1.1" }, "passa": { @@ -588,7 +646,6 @@ "extras": [ "tests" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "path": "." }, "pathlib2": { @@ -596,7 +653,7 @@ "sha256:8eb170f8d0d61825e09a95b38be068299ddeda82f35e96c3301a8a5e7604cb83", "sha256:d1aa2a11ba7b8f7b21ab852b1fb5afb277e1bb99d5dfc663380b5015c0d80c5a" ], - "markers": "python_version < '3.6' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version < '3.5' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.3.2" }, "pip-shims": { @@ -646,32 +703,30 @@ "sha256:78f3f434bcc5d6ee09020f92ba487f95ba50f1e3ef83ae96b9d5ffa1bab25c5d", "sha256:dbae1046def0efb574852fab9e90209b23f556367b5a320c0bcb871c77c3e8cc" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.2.0" }, "pyparsing": { "hashes": [ - "sha256:0832bcf47acd283788593e7a0f542407bd9550a55a8a8435214a1960e04bcb04", - "sha256:fee43f17a9c4087e7ed1605bd6df994c6173c1e977d7ade7b651292fab2bd010" + "sha256:905d8090c335314568b5faee0025b1829f27bb974604a5762a6cdef3a7dfc3b7", + "sha256:f493ee323be1e94929416b3585eefcc04943115cecbaaa35a8c86d1a2368af19" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==2.2.0" + "version": "==2.2.1" }, "pytest": { "hashes": [ - "sha256:2d7c49e931316cc7d1638a3e5f54f5d7b4e5225972b3c9838f3584788d27f349", - "sha256:ad0c7db7b5d4081631e0155f5c61b80ad76ce148551aaafe3a718d65a7508b18" + "sha256:0a72d8a9f559c006ba153e0c9b4838efd7b656cf1f993747ba7128770d6eb12c", + "sha256:95529588ff4e85114a0b0ad8e9cf0131ca47d46b28230e25366c5aba66b1d854" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==3.7.4" + "version": "==3.8.1" }, "pytest-cov": { "hashes": [ - "sha256:03aa752cf11db41d281ea1d807d954c4eda35cfa1b21d6971966cc041bbf6e2d", - "sha256:890fe5565400902b0c78b5357004aab1c814115894f4f21370e2433256a3eeec" + "sha256:513c425e931a0344944f84ea47f3956be0e416d95acbd897a44970c8d926d5d7", + "sha256:e360f048b7dae3f2f2a9a4d067b2dd6b6a015d384d1577c994a43f3f7cbad762" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==2.5.1" + "version": "==2.6.0" }, "pytest-forked": { "hashes": [ @@ -697,18 +752,11 @@ "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.23.0" }, - "pytoml": { - "hashes": [ - "sha256:42f76a696182570e93581e763da033c1de484973bad82458387b6dee6c184cbc" - ], - "version": "==0.1.19" - }, "pytz": { "hashes": [ "sha256:a061aa0a9e06881eb8b3b2b43f05b9439d6583c206d0a6c340ff72a7b6669053", "sha256:ffb9ef1de172603304d9d2819af6f5ece76f2e85ec10692a524dd876e72bf277" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2018.5" }, "requests": { @@ -716,7 +764,6 @@ "sha256:63b52e3c866428a224f97cab011de738c36aec0185aa91cfacd418b5d58911d1", "sha256:ec22d826a36ed72a7358ff3fe56cbd4ba69dd7a6718ffd450ff0e9df7a47ce6a" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.19.1" }, "requests-toolbelt": { @@ -728,19 +775,19 @@ }, "requirementslib": { "hashes": [ - "sha256:7288ec80fa62b78c6193eca85882605c4cdbb60361fc62478bd4a913c0b54400", - "sha256:8bb1b156d8b13337eab359273605b036d60735b350019addabb054e8a89a96f6" + "sha256:90151d8963f814e17190e067b60e92fb35fd1bc46c99f8dba3d7b0d93a3dd958", + "sha256:c3aeaa4e0b80843ba65a68878293e07ea52a8d0706dbba86b02dad6cd20ef2dd" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==1.1.5" + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==1.1.6" }, "resolvelib": { "hashes": [ - "sha256:d52f2c0762deeb2a4cc34a84371a7a5ac85e111bdc69ce9ae729d8d636606ad6", - "sha256:eb759d43bbf50de9bf36afb9f6c269fabf9ff49084dbfad4ba67252d134bf4b5" + "sha256:6c4c6690b0bdd78bcc002e1a5d1b6abbde58c694a6ea1838f165b20d2c943db7", + "sha256:8734e53271ef98f38a2c99324d5e7905bc00c97dc3fc5bb7d83c82a979e71c04" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==0.2.1" + "version": "==0.2.2" }, "scandir": { "hashes": [ @@ -756,7 +803,7 @@ "sha256:c9009c527929f6e25604aec39b0a43c3f831d2947d89d6caaab22f057b7055c8", "sha256:f5c71e29b4e2af7ccdc03a020c626ede51da471173b4a6ad1e904f2b2e04b4bd" ], - "markers": "python_version < '3.5' and python_version < '3.6' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5' and python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "python_version < '3.5' and python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.9.0" }, "six": { @@ -764,7 +811,6 @@ "sha256:70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9", "sha256:832dc0e10feb1aa2c68dcc57dbb658f1c7e65b9b61af69048abc87a2db00a0eb" ], - "markers": "python_version < '3.6' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.6' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.11.0" }, "snowballstemmer": { @@ -772,16 +818,14 @@ "sha256:919f26a68b2c17a7634da993d91339e288964f93c274f1343e3bbbe2096e1128", "sha256:9f3bcd3c401c3e862ec0ebe6d2c069ebc012ce142cce209c098ccb5b09136e89" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.2.1" }, "sphinx": { "hashes": [ - "sha256:95acd6648902333647a0e0564abdb28a74b0a76d2333148aa35e5ed1f56d3c4b", - "sha256:c091dbdd5cc5aac6eb95d591a819fd18bccec90ffb048ec465b165a48b839b45" + "sha256:652eb8c566f18823a022bb4b6dbc868d366df332a11a0226b5bc3a798a479f17", + "sha256:d222626d8356de702431e813a05c68a35967e3d66c6cd1c2c89539bb179a7464" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==1.8.0" + "version": "==1.8.1" }, "sphinx-rtd-theme": { "hashes": [ @@ -795,7 +839,6 @@ "sha256:68ca7ff70785cbe1e7bccc71a48b5b6d965d79ca50629606c7861a21b206d9dd", "sha256:9de47f375baf1ea07cdb3436ff39d7a9c76042c10a769c52353ec46e4e8fc3b9" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.1.0" }, "toml": { @@ -807,11 +850,11 @@ }, "tomlkit": { "hashes": [ - "sha256:618b057b96b488bb858102bdb38dd9d451c0617667031e320efea2392a39bec4", - "sha256:6856b5395f7c509baad1911aa3940b3c2fb33f53aff968ed1596c393ccea98e5" + "sha256:8ab16e93162fc44d3ad83d2aa29a7140b8f7d996ae1790a73b9a7aed6fb504ac", + "sha256:ca181cee7aee805d455628f7c94eb8ae814763769a93e69157f250fe4ebe1926" ], "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", - "version": "==0.4.3" + "version": "==0.4.4" }, "towncrier": { "hashes": [ @@ -825,7 +868,6 @@ "sha256:18f1818ce951aeb9ea162ae1098b43f583f7d057b34d706f66939353d1208889", "sha256:df02c0650160986bac0218bb07952245fc6960d23654648b5d5526ad5a4128c9" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1'", "version": "==4.26.0" }, "twine": { @@ -841,7 +883,7 @@ "sha256:57dcf675a99b74d64dacf6fba08fb17cf7e3d5fdff53d4a30ea2a5e7e52543d4", "sha256:a4c8473ce11a65999c8f59cb093e70686b6c84c98df58c1dae9b3b196089858a" ], - "markers": "python_version < '3.5' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5' and python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "markers": "(python_version >= '2.7' and python_version < '2.8') or (python_version >= '3.4' and python_version < '3.5') and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version < '3.5'", "version": "==3.6.6" }, "urllib3": { @@ -849,9 +891,16 @@ "sha256:a68ac5e15e76e7e5dd2b8f94007233e01effe3e50e8daddf69acfd81cb686baf", "sha256:b5725a0bd4ba422ab0e66e89e030c806576753ea3ee08554382c14e685d117b5" ], - "markers": "python_version < '4' and python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.23" }, + "virtualenv": { + "hashes": [ + "sha256:2ce32cd126117ce2c539f0134eb89de91a8413a29baac49cbab3eb50e2026669", + "sha256:ca07b4c0b54e14a91af9f34d0919790b016923d157afda5efdde55c96718f752" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==16.0.0" + }, "vistir": { "extras": [ "spinner" @@ -868,8 +917,15 @@ "sha256:0a2e54558a0628f2145d2fc822137e322412115173e8a2ddbe1c9024338ae83c", "sha256:80044e51ec5bbf6c894ba0bc48d26a8c20a9ba629f4ca19ea26ecfcf87685f5f" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3' or python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.31.1" + }, + "yaspin": { + "hashes": [ + "sha256:36fdccc5e0637b5baa8892fe2c3d927782df7d504e9020f40eb2c1502518aa5a", + "sha256:8e52bf8079a48e2a53f3dfeec9e04addb900c101d1591c85df69cf677d3237e7" + ], + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", + "version": "==0.14.0" } } } diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..8213302 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,2 @@ +sphinx +sphinx_rtd_theme diff --git a/news/53.feature.rst b/news/53.feature.rst new file mode 100644 index 0000000..2589034 --- /dev/null +++ b/news/53.feature.rst @@ -0,0 +1 @@ +Refactored and restructured the internals for improved organization and separation of concerns. diff --git a/setup.cfg b/setup.cfg index 98ea198..e6879b5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -37,20 +37,27 @@ python_requires = >=2.7,!=3.0,!=3.1,!=3.2,!=3.3 setup_requires = setuptools>=36.2.2 install_requires = appdirs + cached-property distlib + installer packaging + packagebuilder pip-shims>=0.1.2 plette[validation]>=0.2.2 requests resolvelib>=0.2.1,!=1.0.0.dev0 + backports.functools_lru_cache; python_version<='2.7' requirementslib>=1.1.1 six + virtualenv vistir[spinner]>=0.1.4 [options.extras_require] pack = invoke parver +virtualenv = + mork tests = pytest-xdist pytest-timeout diff --git a/src/passa/actions/__init__.py b/src/passa/actions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/passa/actions/add.py b/src/passa/actions/add.py new file mode 100644 index 0000000..6cfb3e2 --- /dev/null +++ b/src/passa/actions/add.py @@ -0,0 +1,57 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + +import itertools +import sys + + +def add_packages(packages=[], editables=[], project=None, dev=False, sync=False, clean=False): + from passa.models.lockers import PinReuseLocker + from passa.operations.lock import lock + + lines = list(itertools.chain( + packages, + ("-e {}".format(e) for e in editables), + )) + + project = project + for line in lines: + try: + project.add_line_to_pipfile(line, develop=dev) + except (TypeError, ValueError) as e: + print("Cannot add {line!r} to Pipfile: {error}".format( + line=line, error=str(e), + ), file=sys.stderr) + return 2 + + prev_lockfile = project.lockfile + + locker = PinReuseLocker(project) + success = lock(locker) + if not success: + return 1 + + project._p.write() + project._l.write() + print("Written to project at", project.root) + + if not sync: + return + + from installer.synchronizer import Synchronizer + from installer.operations import sync + + lockfile_diff = project.difference_lockfile(prev_lockfile) + default = any(lockfile_diff.default) + develop = any(lockfile_diff.develop) + + syncer = Synchronizer( + project, default=default, develop=develop, + clean_unneeded=clean + ) + success = sync(syncer) + if not success: + return 1 + + print("Synchronized project at", project.root) diff --git a/src/passa/actions/clean.py b/src/passa/actions/clean.py new file mode 100644 index 0000000..d4b8193 --- /dev/null +++ b/src/passa/actions/clean.py @@ -0,0 +1,17 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + + +def clean(project, default=True, dev=False, sync=True): + from installer.synchronizer import Cleaner + from installer.operations import clean + + cleaner = Cleaner(project, default=default, develop=dev, sync=sync) + + success = clean(cleaner) + if not success: + return 1 + + if sync: + print("Cleaned project at", project.root) diff --git a/src/passa/actions/freeze.py b/src/passa/actions/freeze.py new file mode 100644 index 0000000..ca4dbb2 --- /dev/null +++ b/src/passa/actions/freeze.py @@ -0,0 +1,93 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + +import contextlib +import io +import itertools +import sys + +import vistir.misc + + +def _source_as_lines(source, extra): + url = source["url"] + if extra: + lines = ["--extra-index-url {}".format(url)] + else: + lines = ["--index-url {}".format(url)] + if not source.get("verify_ssl", True): + lines = ["--trusted-host {}".format(url)] + return lines + + +def _requirement_as_line(requirement, sources, include_hashes): + if requirement.index: + sources = sources + else: + sources = None + line = vistir.misc.to_text( + requirement.as_line(sources=sources, include_hashes=include_hashes) + ) + return line + + +@contextlib.contextmanager +def open_for_output(filename): + if filename is None: + yield sys.stdout + return + with io.open(filename, "w", encoding="utf-8", newline="\n") as f: + yield f + + +def freeze(project=None, default=True, dev=True, include_hashes=None, target=None): + from requirementslib import Requirement + + lockfile = project.lockfile + if not lockfile: + print("Pipfile.lock is required to export.", file=sys.stderr) + return 1 + + section_names = [] + if default: + section_names.append("default") + if dev: + section_names.append("develop") + requirements = [ + Requirement.from_pipfile(key, entry._data) + for key, entry in itertools.chain.from_iterable( + lockfile.get(name, {}).items() + for name in section_names + ) + ] + + if include_hashes is None: + include_hashes = all(r.is_named for r in requirements) + + sources = lockfile.meta.sources._data + + source_lines = list(vistir.misc.dedup(itertools.chain( + itertools.chain.from_iterable( + _source_as_lines(source, False) + for source in sources[:1] + ), + itertools.chain.from_iterable( + _source_as_lines(source, True) + for source in sources[1:] + ), + ))) + + requirement_lines = sorted(vistir.misc.dedup( + _requirement_as_line(requirement, sources, include_hashes) + for requirement in requirements + )) + + with open_for_output(target) as f: + for line in source_lines: + f.write(line) + f.write("\n") + f.write("\n") + for line in requirement_lines: + f.write(line) + f.write("\n") diff --git a/src/passa/actions/init.py b/src/passa/actions/init.py new file mode 100644 index 0000000..baf8445 --- /dev/null +++ b/src/passa/actions/init.py @@ -0,0 +1,54 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + +import io +import os + +import six + +import packagebuilder + +import plette +import vistir + + +def get_sources(urls, trusted_hosts): + trusted_hosts = [six.moves.urllib.parse.urlparse(url).netloc for url in trusted_hosts] + sources = [] + for url in urls: + parsed_url = six.moves.urllib.parse.urlparse(url) + netloc = parsed_url.netloc + if '@' in netloc: + _, _, netloc = netloc.rpartition('@') + name, _, _ = netloc.partition('.') # Just use the domain name as the source name + verify_ssl = True + if netloc in trusted_hosts: + verify_ssl = False + sources.append({"url": url, "name": name, "verify_ssl": verify_ssl}) + return sources + + +def init_project(root=None, python_version=None): + pipfile_path = os.path.join(root, "Pipfile") + if os.path.isfile(pipfile_path): + raise RuntimeError("{0!r} is already a Pipfile project".format(root)) + if not os.path.exists(root): + vistir.path.mkdir_p(root, mode=0o755) + sources = packagebuilder.get_sources() + data = { + "source": sources, + "packages": {}, + "dev-packages": {}, + } + if python_version: + data["requires"] = {"python_version": python_version} + return create_project(pipfile_path=pipfile_path, data=data) + + +def create_project(pipfile_path, data={}): + pipfile = plette.pipfiles.Pipfile(data=data) + with io.open(pipfile_path, "w") as fh: + pipfile.dump(fh) + print("Successfully created new pipfile at {0!r}".format(pipfile_path)) + return 0 diff --git a/src/passa/actions/install.py b/src/passa/actions/install.py new file mode 100644 index 0000000..c920906 --- /dev/null +++ b/src/passa/actions/install.py @@ -0,0 +1,32 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + + +def install(project=None, check=True, dev=False, clean=True): + from passa.models.lockers import BasicLocker + from passa.operations.lock import lock + + project = project + + if not check or not project.is_synced(): + locker = BasicLocker(project) + success = lock(locker) + if not success: + return 1 + project._l.write() + print("Written to project at", project.root) + + from installer.synchronizer import Synchronizer + from installer.operations import sync + + syncer = Synchronizer( + project, default=True, develop=dev, + clean_unneeded=clean, + ) + + success = sync(syncer) + if not success: + return 1 + + print("Synchronized project at", project.root) diff --git a/src/passa/actions/lock.py b/src/passa/actions/lock.py new file mode 100644 index 0000000..7c09469 --- /dev/null +++ b/src/passa/actions/lock.py @@ -0,0 +1,17 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + + +def lock(project=None): + from passa.models.lockers import BasicLocker + from passa.operations.lock import lock + + project = project + locker = BasicLocker(project) + success = lock(locker) + if not success: + return + + project._l.write() + print("Written to project at", project.root) diff --git a/src/passa/actions/remove.py b/src/passa/actions/remove.py new file mode 100644 index 0000000..2fcba75 --- /dev/null +++ b/src/passa/actions/remove.py @@ -0,0 +1,38 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + + +def remove(project=None, only="default", packages=[], clean=True, sync=False): + from passa.models.lockers import PinReuseLocker + from passa.operations.lock import lock + + default = (only != "dev") + develop = (only != "default") + + project = project + project.remove_keys_from_pipfile( + packages, default=default, develop=develop, + ) + + locker = PinReuseLocker(project) + success = lock(locker) + if not success: + return 1 + + project._p.write() + project._l.write() + print("Written to project at", project.root) + + if not clean: + return + + from installer.synchronizer import Cleaner + from installer.operations import clean + + cleaner = Cleaner(project, default=True, develop=True) + success = clean(cleaner) + if not success: + return 1 + + print("Cleaned project at", project.root) diff --git a/src/passa/actions/sync.py b/src/passa/actions/sync.py new file mode 100644 index 0000000..e785627 --- /dev/null +++ b/src/passa/actions/sync.py @@ -0,0 +1,20 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + + +def sync(project=None, dev=False, clean=True): + from installer.synchronizers import Synchronizer + from installer.operations import sync + + project = project + syncer = Synchronizer( + project, default=True, develop=dev, + clean_unneeded=clean, + ) + + success = sync(syncer) + if not success: + return 1 + + print("Synchronized project at", project.root) diff --git a/src/passa/actions/upgrade.py b/src/passa/actions/upgrade.py new file mode 100644 index 0000000..7fd3c1e --- /dev/null +++ b/src/passa/actions/upgrade.py @@ -0,0 +1,52 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + +import sys + + +def upgrade(project=None, strategy="only-if-needed", sync=True, packages=[]): + from passa.models.lockers import EagerUpgradeLocker, PinReuseLocker + from passa.operations.lock import lock + + for package in packages: + if not project.contains_key_in_pipfile(package): + print("{package!r} not found in Pipfile".format( + package=package, + ), file=sys.stderr) + return 2 + + project.remove_keys_from_lockfile(packages) + + prev_lockfile = project.lockfile + + if strategy == "eager": + locker = EagerUpgradeLocker(project, packages) + else: + locker = PinReuseLocker(project) + success = lock(locker) + if not success: + return 1 + + project._l.write() + print("Written to project at", project.root) + + if not sync: + return + + from installer.operations import sync + from installer.synchronizer import Synchronizer + + lockfile_diff = project.difference_lockfile(prev_lockfile) + default = bool(any(lockfile_diff.default)) + develop = bool(any(lockfile_diff.develop)) + + syncer = Synchronizer( + project, default=default, develop=develop, + clean_unneeded=False, + ) + success = sync(syncer) + if not success: + return 1 + + print("Synchronized project at", project.root) diff --git a/src/passa/cli/__init__.py b/src/passa/cli/__init__.py index cb503e8..b6891d3 100644 --- a/src/passa/cli/__init__.py +++ b/src/passa/cli/__init__.py @@ -34,7 +34,7 @@ def main(argv=None): continue parser = subparsers.add_parser(klass.name, help=klass.description) command = klass(parser) - parser.set_defaults(func=command.main) + parser.set_defaults(func=command.run) options = root_parser.parse_args(argv) diff --git a/src/passa/cli/_base.py b/src/passa/cli/_base.py index 68e0e34..0ca4868 100644 --- a/src/passa/cli/_base.py +++ b/src/passa/cli/_base.py @@ -6,31 +6,7 @@ import os import sys -import tomlkit.exceptions - - -def build_project(root): - # This is imported lazily to reduce import overhead. Not evey command - # needs the project instance. - from passa.internals.projects import Project - root = os.path.abspath(root) - if not os.path.isfile(os.path.join(root, "Pipfile")): - raise argparse.ArgumentError( - "{0!r} is not a Pipfile project".format(root), - ) - try: - project = Project(root) - except tomlkit.exceptions.ParseError as e: - raise argparse.ArgumentError( - "failed to parse Pipfile: {0!r}".format(str(e)), - ) - return project - - -# Better error reporting. Recent argparse would emit something like -# "invalid project root value: 'xxxxxx'". The str() wrapper is needed to -# keep Python 2 happy :( -build_project.__name__ = str("project root") +from .options import project class BaseCommand(object): @@ -38,19 +14,30 @@ class BaseCommand(object): """ name = None description = None - parsed_main = None - - def __init__(self, parser): + default_arguments = [project] + arguments = [] + + def __init__(self, parser=None): + if not parser: + parser = argparse.ArgumentParser( + prog=os.path.basename(sys.argv[0]), + description="Base argument parser for passa" + ) self.parser = parser self.add_arguments() @classmethod - def run_current_module(cls): + def build_parser(cls): parser = argparse.ArgumentParser( prog="passa {}".format(cls.name), description=cls.description, ) - cls(parser)() + return cls(parser) + + @classmethod + def run_parser(cls): + parser = cls.build_parser() + parser() def __call__(self, argv=None): options = self.parser.parse_args(argv) @@ -58,16 +45,17 @@ def __call__(self, argv=None): if result is not None: sys.exit(result) + def add_default_arguments(self): + for arg in self.default_arguments: + arg.add_to_parser(self.parser) + def add_arguments(self): - self.parser.add_argument( - "--project", - metavar="project", - default=os.getcwd(), - type=build_project, - help="path to project root (directory containing Pipfile)", - ) + self.add_default_arguments() + for arg in self.arguments: + arg.add_to_parser(self.parser) def main(self, options): - # This __dict__ access is needed for Python 2 to prevent Python from - # wrapping parsed_main into an unbounded method. - return type(self).__dict__["parsed_main"](options) + return self.run(options) + + def run(self, options): + raise NotImplementedError diff --git a/src/passa/cli/add.py b/src/passa/cli/add.py index 26ce0ed..2635b98 100644 --- a/src/passa/cli/add.py +++ b/src/passa/cli/add.py @@ -2,98 +2,28 @@ from __future__ import absolute_import, print_function, unicode_literals -import itertools -import sys - +from ..actions.add import add_packages from ._base import BaseCommand - - -def main(options): - from passa.internals.lockers import PinReuseLocker - from passa.operations.lock import lock - - lines = list(itertools.chain( - options.requirement_lines, - ("-e {}".format(e) for e in options.editable_lines), - )) - - project = options.project - for line in lines: - try: - project.add_line_to_pipfile(line, develop=options.dev) - except (TypeError, ValueError) as e: - print("Cannot add {line!r} to Pipfile: {error}".format( - line=line, error=str(e), - ), file=sys.stderr) - return 2 - - prev_lockfile = project.lockfile - - locker = PinReuseLocker(project) - success = lock(locker) - if not success: - return 1 - - project._p.write() - project._l.write() - print("Written to project at", project.root) - - if not options.sync: - return - - from passa.internals.synchronizers import Synchronizer - from passa.operations.sync import sync - - lockfile_diff = project.difference_lockfile(prev_lockfile) - default = bool(any(lockfile_diff.default)) - develop = bool(any(lockfile_diff.develop)) - - syncer = Synchronizer( - project, default=default, develop=develop, - clean_unneeded=False, - ) - success = sync(syncer) - if not success: - return 1 - - print("Synchronized project at", project.root) +from .options import package_group, clean_group class Command(BaseCommand): name = "add" description = "Add packages to project." - parsed_main = main + arguments = [package_group, clean_group] - def add_arguments(self): - super(Command, self).add_arguments() - self.parser.add_argument( - "requirement_lines", metavar="requirement", - nargs="*", - help="requirement to add (can be used multiple times)", - ) - self.parser.add_argument( - "-e", "--editable", - metavar="requirement", dest="editable_lines", - action="append", default=[], - help="editable requirement to add (can be used multiple times)", - ) - self.parser.add_argument( - "--dev", - action="store_true", - help="add packages to [dev-packages]", - ) - self.parser.add_argument( - "--no-sync", dest="sync", - action="store_false", default=True, - help="do not synchronize the environment", - ) - - def main(self, options): - if not options.editable_lines and not options.requirement_lines: + def run(self, options): + if not options.editables and not options.packages: self.parser.error("Must supply either a requirement or --editable") - return super(Command, self).main(options) + return add_packages( + packages=options.packages, + editables=options.editables, + project=options.project, + dev=options.dev, + clean=options.clean + ) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/cli/clean.py b/src/passa/cli/clean.py index cd1b679..a74d814 100644 --- a/src/passa/cli/clean.py +++ b/src/passa/cli/clean.py @@ -2,37 +2,23 @@ from __future__ import absolute_import, print_function, unicode_literals +from ..actions.clean import clean from ._base import BaseCommand - - -def main(options): - from passa.internals.synchronizers import Cleaner - from passa.operations.sync import clean - - project = options.project - cleaner = Cleaner(project, default=True, develop=options.dev) - - success = clean(cleaner) - if not success: - return 1 - - print("Cleaned project at", project.root) +from .options import dev, no_default, sync_group class Command(BaseCommand): name = "clean" description = "Uninstall unlisted packages from the environment." - parsed_main = main - - def add_arguments(self): - super(Command, self).add_arguments() - self.parser.add_argument( - "--no-dev", dest="dev", - action="store_false", default=True, - help="uninstall develop packages, only keep default ones", + arguments = [dev, no_default, sync_group] + + def run(self, options): + return clean( + project=options.project, default=options.default, dev=options.dev, + sync=options.sync ) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/cli/freeze.py b/src/passa/cli/freeze.py index 6ca5717..053c727 100644 --- a/src/passa/cli/freeze.py +++ b/src/passa/cli/freeze.py @@ -2,137 +2,23 @@ from __future__ import absolute_import, print_function, unicode_literals -import contextlib -import io -import itertools -import sys - -import six -import vistir.misc - +from ..actions.freeze import freeze from ._base import BaseCommand - - -def _source_as_lines(source, extra): - url = source["url"] - if extra: - lines = ["--extra-index-url {}".format(url)] - else: - lines = ["--index-url {}".format(url)] - if not source.get("verify_ssl", True): - lines = ["--trusted-host {}".format(url)] - return lines - - -def _requirement_as_line(requirement, sources, include_hashes): - if requirement.index: - sources = sources - else: - sources = None - line = requirement.as_line(sources=sources, include_hashes=include_hashes) - if not isinstance(line, six.text_type): - line = line.decode("utf-8") - return line - - -@contextlib.contextmanager -def open_for_output(filename): - if filename is None: - yield sys.stdout - return - with io.open(filename, "w", encoding="utf-8", newline="\n") as f: - yield f - - -def main(options): - from requirementslib import Requirement - - lockfile = options.project.lockfile - if not lockfile: - print("Pipfile.lock is required to export.", file=sys.stderr) - return 1 - - section_names = [] - if options.default: - section_names.append("default") - if options.dev: - section_names.append("develop") - requirements = [ - Requirement.from_pipfile(key, entry._data) - for key, entry in itertools.chain.from_iterable( - lockfile.get(name, {}).items() - for name in section_names - ) - ] - - include_hashes = options.include_hashes - if include_hashes is None: - include_hashes = all(r.is_named for r in requirements) - - sources = lockfile.meta.sources._data - - source_lines = list(vistir.misc.dedup(itertools.chain( - itertools.chain.from_iterable( - _source_as_lines(source, False) - for source in sources[:1] - ), - itertools.chain.from_iterable( - _source_as_lines(source, True) - for source in sources[1:] - ), - ))) - - requirement_lines = sorted(vistir.misc.dedup( - _requirement_as_line(requirement, sources, include_hashes) - for requirement in requirements - )) - - with open_for_output(options.target) as f: - for line in source_lines: - f.write(line) - f.write("\n") - f.write("\n") - for line in requirement_lines: - f.write(line) - f.write("\n\n") +from .options import dev, include_hashes_group, no_default, target class Command(BaseCommand): name = "freeze" description = "Export project depenencies to requirements.txt." - parsed_main = main + arguments = [dev, no_default, target, include_hashes_group] - def add_arguments(self): - super(Command, self).add_arguments() - self.parser.add_argument( - "--target", - default=None, - help="file to export into (default is to print to stdout)", - ) - self.parser.add_argument( - "--dev", - action="store_true", default=False, - help="include development packages in requirements.txt", - ) - self.parser.add_argument( - "--no-default", dest="default", - action="store_false", default=True, - help="do not include default packages in requirements.txt", - ) - include_hashes_group = self.parser.add_mutually_exclusive_group() - include_hashes_group.add_argument( - "--include-hashes", dest="include_hashes", - action="store_true", - help="output hashes in requirements.txt (default is to guess)", - ) - include_hashes_group.add_argument( - "--no-include-hashes", dest="include_hashes", - action="store_false", - help=("do not output hashes in requirements.txt " - "(default is to guess)"), + def run(self, options): + return freeze( + project=options.project, default=options.default, dev=options.dev, + include_hashes=options.include_hashes ) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/cli/init.py b/src/passa/cli/init.py new file mode 100644 index 0000000..95ce8d8 --- /dev/null +++ b/src/passa/cli/init.py @@ -0,0 +1,32 @@ +# -*- coding=utf-8 -*- + +from __future__ import absolute_import, print_function, unicode_literals + +import argparse +import os + +from ..actions.init import init_project +from ._base import BaseCommand +from .options import new_project_group + + +class Command(BaseCommand): + + name = "init" + description = "Create a new project." + default_arguments = [] + arguments = [new_project_group] + + def run(self, options): + pipfile_path = os.path.join(options.project, "Pipfile") + if os.path.exists(pipfile_path): + raise argparse.ArgumentError( + "{0!r} is already a Pipfile project".format(options.project), + ) + return init_project( + root=options.project, python_version=options.python_version + ) + + +if __name__ == "__main__": + Command.run_parser() diff --git a/src/passa/cli/install.py b/src/passa/cli/install.py index f47377b..1c0b459 100644 --- a/src/passa/cli/install.py +++ b/src/passa/cli/install.py @@ -2,62 +2,21 @@ from __future__ import absolute_import, print_function, unicode_literals +from ..actions.install import install from ._base import BaseCommand - - -def main(options): - from passa.internals.lockers import BasicLocker - from passa.operations.lock import lock - - project = options.project - - if not options.check or not project.is_synced(): - locker = BasicLocker(project) - success = lock(locker) - if not success: - return 1 - project._l.write() - print("Written to project at", project.root) - - from passa.internals.synchronizers import Synchronizer - from passa.operations.sync import sync - - syncer = Synchronizer( - project, default=True, develop=options.dev, - clean_unneeded=options.clean, - ) - - success = sync(syncer) - if not success: - return 1 - - print("Synchronized project at", project.root) +from .options import dev, no_check, no_clean class Command(BaseCommand): name = "install" description = "Generate Pipfile.lock to synchronize the environment." - parsed_main = main - - def add_arguments(self): - super(Command, self).add_arguments() - self.parser.add_argument( - "--no-check", dest="check", - action="store_false", default=True, - help="do not check if Pipfile.lock is update, always resolve", - ) - self.parser.add_argument( - "--dev", - action="store_true", - help="install develop packages", - ) - self.parser.add_argument( - "--no-clean", dest="clean", - action="store_false", default=True, - help="do not uninstall packages not specified in Pipfile.lock", - ) + arguments = [no_check, dev, no_clean] + + def run(self, options): + return install(project=options.project, check=options.check, dev=options.dev, + clean=options.clean) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/cli/lock.py b/src/passa/cli/lock.py index 67b1d11..9b0651a 100644 --- a/src/passa/cli/lock.py +++ b/src/passa/cli/lock.py @@ -2,28 +2,17 @@ from __future__ import absolute_import, print_function, unicode_literals +from ..actions.lock import lock from ._base import BaseCommand -def main(options): - from passa.internals.lockers import BasicLocker - from passa.operations.lock import lock - - project = options.project - locker = BasicLocker(project) - success = lock(locker) - if not success: - return - - project._l.write() - print("Written to project at", project.root) - - class Command(BaseCommand): name = "lock" description = "Generate Pipfile.lock." - parsed_main = main + + def run(self, options): + return lock(project=options.project) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/cli/options.py b/src/passa/cli/options.py new file mode 100644 index 0000000..d2a6378 --- /dev/null +++ b/src/passa/cli/options.py @@ -0,0 +1,206 @@ +# -*- coding=utf-8 -*- +from __future__ import absolute_import + +import argparse +import inspect +import os +import sys + +import six +import tomlkit.exceptions + +import passa.models.projects +import vistir + + +PYTHON_VERSION = ".".join(str(v) for v in sys.version_info[:2]) + + +class Project(passa.models.projects.Project): + def __init__(self, root, *args, **kwargs): + root = vistir.compat.Path(root).absolute() + pipfile = root.joinpath("Pipfile") + if not pipfile.is_file(): + raise argparse.ArgumentError( + project, "{0!r} is not a Pipfile project".format(root.as_posix()), + ) + try: + super(Project, self).__init__(root.as_posix(), *args, **kwargs) + except tomlkit.exceptions.ParseError as e: + raise argparse.ArgumentError( + project, "failed to parse Pipfile: {0!r}".format(str(e)), + ) + + def __name__(self): + return "Project Root" + + +class OptionMeta(type): + + @property + def action_map(self): + action_map = getattr(self, '_action_map', None) + if not action_map: + self.action_map = { + name.strip("_").replace("Action", ""): obj + for name, obj in inspect.getmembers(argparse) + if name.startswith('_') and name.endswith('Action') + } + return self._action_map + + @action_map.setter + def action_map(self, action_map): + self._action_map = action_map + + +@six.add_metaclass(OptionMeta) +class Option(object): + def __init__(self, *args, **kwargs): + self.args = list(args) + self.kwargs = kwargs.copy() + if "dest" not in kwargs and not args[0].startswith("-"): + dest = list(args).pop(0) + else: + dest = kwargs.pop("dest", args[0].lstrip("-").replace("-", "_")) + action = kwargs.pop("action", None) + if not action: + if 'const' in kwargs: + action = 'store_const' + else: + action = 'store' + self.action = self.get_option(action, args, dest, **kwargs) + + @classmethod + def get_option(cls, action, option_strings, dest, *args, **kwargs): + if action: + action = action.title().replace("_", "") + return cls.action_map[action](list(option_strings), dest, *args, **kwargs) + return + + def add_to_parser(self, parser): + parser.add_argument(*self.args, **self.kwargs) + + def add_to_group(self, group): + group.add_argument(*self.args, **self.kwargs) + + +class ArgumentGroup(object): + def __init__(self, name, parser=None, is_mutually_exclusive=False, required=False, options=[]): + self.name = name + self.options = options + self.parser = parser + self.required = required + self.is_mutually_exclusive = is_mutually_exclusive + self.argument_group = None + + def add_to_parser(self, parser): + group = None + if self.is_mutually_exclusive: + group = parser.add_mutually_exclusive_group(required=self.required) + else: + group = parser.add_argument_group() + for option in self.options: + option.add_to_group(group) + self.argument_group = group + self.parser = parser + + def add_to_group(self, group): + self.add_to_parser(group) + + +project = Option( + "--project", metavar="project", default=os.getcwd(), type=Project, + help="path to project root (directory containing Pipfile)", +) + +new_project = Option( + "--project", metavar="project", default=os.getcwd(), type=str, + help="path to project root (directory containing Pipfile)", +) + +python_version = Option( + "--py-version", "--python-version", "--requires-python", metavar="python_version", + dest="python_version", default=PYTHON_VERSION, type=str, + help="required minor python version for the project" +) + +packages = Option( + "packages", metavar="package", nargs="*", + help="requirement to add (can be used multiple times)", +) + +editable = Option( + '-e', '--editable', dest='editables', nargs="*", default=[], metavar='path/vcs', + help="editable requirement to add (can be used multiple times)", +) + +dev = Option( + "--dev", action="store_true", default=False, + help="Use [dev-packages] for install/freeze/uninstall operations", +) + +no_sync = Option( + "--no-sync", dest="sync", action="store_false", default=True, + help="do not synchronize the environment", +) + +sync = Option( + "--sync", dest="sync", action="store_true", help="synchronize the environment", + default=False +) + +target = Option( + "-t", "--target", default=None, + help="file to export into (default is to print to stdout)" +) + +no_default = Option( + "--no-default", dest="default", action="store_false", default=True, + help="do not include default packages when exporting, importing, or cleaning" +) + +include_hashes = Option( + "--include-hashes", dest="include_hashes", action="store_true", + help="output hashes in requirements.txt (default is to guess)", +) + +no_include_hashes = Option( + "--no-include-hashes", dest="include_hashes", action="store_false", + help="do not output hashes in requirements.txt (default is to guess)", +) + +no_check = Option( + "--no-check", dest="check", action="store_false", default=True, + help="do not check if Pipfile.lock is up to date, always resolve", +) + +no_clean = Option( + "--no-clean", dest="clean", action="store_false", default=True, + help="do not remove packages not specified in Pipfile.lock", +) + +clean = Option( + "--clean", dest="clean", action="store_true", default=False, + help="remove packages not specified in Pipfile.lock", +) +dev_only = Option( + "--dev", dest="only", action="store_const", const="dev", + help="only try to modify [dev-packages]", +) + +default_only = Option( + "--default", dest="only", action="store_const", const="default", + help="only try to modify [default]", +) + +strategy = Option( + "--strategy", choices=["eager", "only-if-needed"], default="only-if-needed", + help="how dependency upgrading is handled", +) + +include_hashes_group = ArgumentGroup("include_hashes", is_mutually_exclusive=True, options=[include_hashes, no_include_hashes]) +dev_group = ArgumentGroup("dev", is_mutually_exclusive="True", options=[dev_only, default_only]) +new_project_group = ArgumentGroup("new-project", options=[new_project, python_version]) +clean_group = ArgumentGroup("clean", is_mutually_exclusive=True, options=[clean, no_clean]) +sync_group = ArgumentGroup("sync", is_mutually_exclusive=True, options=[sync, no_sync]) +package_group = ArgumentGroup("packages", options=[packages, editable, dev, sync_group]) diff --git a/src/passa/cli/remove.py b/src/passa/cli/remove.py index b1dbfd7..041c195 100644 --- a/src/passa/cli/remove.py +++ b/src/passa/cli/remove.py @@ -2,74 +2,21 @@ from __future__ import absolute_import, print_function, unicode_literals +from ..actions.remove import remove from ._base import BaseCommand - - -def main(options): - from passa.internals.lockers import PinReuseLocker - from passa.operations.lock import lock - - default = (options.only != "dev") - develop = (options.only != "default") - - project = options.project - project.remove_keys_from_pipfile( - options.packages, default=default, develop=develop, - ) - - locker = PinReuseLocker(project) - success = lock(locker) - if not success: - return 1 - - project._p.write() - project._l.write() - print("Written to project at", project.root) - - if not options.clean: - return - - from passa.internals.synchronizers import Cleaner - from passa.operations.sync import clean - - cleaner = Cleaner(project, default=True, develop=True) - success = clean(cleaner) - if not success: - return 1 - - print("Cleaned project at", project.root) +from .options import dev_group, clean_group, sync_group, packages class Command(BaseCommand): name = "remove" description = "Remove packages from project." - parsed_main = main + arguments = [dev_group, clean_group, sync_group, packages] - def add_arguments(self): - super(Command, self).add_arguments() - self.parser.add_argument( - "packages", metavar="package", - nargs="+", - help="package to remove (can be used multiple times)", - ) - dev_group = self.parser.add_mutually_exclusive_group() - dev_group.add_argument( - "--dev", dest="only", - action="store_const", const="dev", - help="only try to remove from [dev-packages]", - ) - dev_group.add_argument( - "--default", dest="only", - action="store_const", const="default", - help="only try to remove from [packages]", - ) - self.parser.add_argument( - "--no-clean", dest="clean", - action="store_false", default=True, - help="do not uninstall packages not specified in Pipfile.lock", - ) + def run(self, options): + return remove(project=options.project, only=options.only, + packages=options.packages, clean=options.clean, sync=options.sync) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/cli/sync.py b/src/passa/cli/sync.py index ade81e0..9a31fe1 100644 --- a/src/passa/cli/sync.py +++ b/src/passa/cli/sync.py @@ -2,45 +2,20 @@ from __future__ import absolute_import, print_function, unicode_literals +from ..actions.sync import sync from ._base import BaseCommand - - -def main(options): - from passa.internals.synchronizers import Synchronizer - from passa.operations.sync import sync - - project = options.project - syncer = Synchronizer( - project, default=True, develop=options.dev, - clean_unneeded=options.clean, - ) - - success = sync(syncer) - if not success: - return 1 - - print("Synchronized project at", project.root) +from .options import dev, clean_group class Command(BaseCommand): name = "sync" description = "Install Pipfile.lock into the environment." - parsed_main = main - - def add_arguments(self): - super(Command, self).add_arguments() - self.parser.add_argument( - "--dev", - action="store_true", - help="install develop packages", - ) - self.parser.add_argument( - "--no-clean", dest="clean", - action="store_false", default=True, - help="do not uninstall packages not specified in Pipfile.lock", - ) + arguments = [dev, clean_group] + + def run(self, options): + return sync(project=options.project, dev=options.dev, clean=options.clean) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/cli/upgrade.py b/src/passa/cli/upgrade.py index 011fff6..c7696c2 100644 --- a/src/passa/cli/upgrade.py +++ b/src/passa/cli/upgrade.py @@ -1,91 +1,21 @@ # -*- coding=utf-8 -*- - from __future__ import absolute_import, print_function, unicode_literals -import sys - +from ..actions.upgrade import upgrade from ._base import BaseCommand - - -def main(options): - from passa.internals.lockers import EagerUpgradeLocker, PinReuseLocker - from passa.operations.lock import lock - - project = options.project - packages = options.packages - for package in packages: - if not project.contains_key_in_pipfile(package): - print("{package!r} not found in Pipfile".format( - package=package, - ), file=sys.stderr) - return 2 - - project.remove_keys_from_lockfile(packages) - - prev_lockfile = project.lockfile - - if options.strategy == "eager": - locker = EagerUpgradeLocker(project, packages) - else: - locker = PinReuseLocker(project) - success = lock(locker) - if not success: - return 1 - - project._l.write() - print("Written to project at", project.root) - - if not options.sync: - return - - from passa.operations.sync import sync - from passa.internals.synchronizers import Synchronizer - - lockfile_diff = project.difference_lockfile(prev_lockfile) - default = bool(any(lockfile_diff.default)) - develop = bool(any(lockfile_diff.develop)) - - syncer = Synchronizer( - project, default=default, develop=develop, - clean_unneeded=False, - ) - success = sync(syncer) - if not success: - return 1 - - print("Synchronized project at", project.root) +from .options import clean_group, sync_group, packages, strategy class Command(BaseCommand): name = "upgrade" description = "Upgrade packages in project." - parsed_main = main + arguments = [packages, strategy, clean_group, sync_group] - def add_arguments(self): - super(Command, self).add_arguments() - self.parser.add_argument( - "packages", metavar="package", - nargs="+", - help="package to upgrade (can be used multiple times)", - ) - self.parser.add_argument( - "--strategy", - choices=["eager", "only-if-needed"], - default="only-if-needed", - help="how dependency upgrading is handled", - ) - self.parser.add_argument( - "--no-sync", dest="sync", - action="store_false", default=True, - help="do not synchronize the environment", - ) - self.parser.add_argument( - "--no-clean", dest="clean", - action="store_false", default=True, - help="do not uninstall packages not specified in Pipfile.lock", - ) + def run(self, options): + return upgrade(project=options.project, strategy=options.strategy, + sync=options.sync, packages=options.packages) if __name__ == "__main__": - Command.run_current_module() + Command.run_parser() diff --git a/src/passa/internals/_pip.py b/src/passa/internals/_pip.py deleted file mode 100644 index f73e241..0000000 --- a/src/passa/internals/_pip.py +++ /dev/null @@ -1,397 +0,0 @@ -# -*- coding=utf-8 -*- - -from __future__ import absolute_import, unicode_literals - -import contextlib -import io -import itertools -import distutils.log -import os - -import distlib.database -import distlib.scripts -import distlib.wheel -import packaging.utils -import pip_shims -import setuptools.dist -import six -import vistir - -from ._pip_shims import VCS_SUPPORT, build_wheel as _build_wheel, unpack_url -from .caches import CACHE_DIR -from .utils import filter_sources - - -@vistir.path.ensure_mkdir_p(mode=0o775) -def _get_src_dir(): - src = os.environ.get("PIP_SRC") - if src: - return src - virtual_env = os.environ.get("VIRTUAL_ENV") - if virtual_env: - return os.path.join(virtual_env, "src") - return os.path.join(os.getcwd(), "src") # Match pip's behavior. - - -def _prepare_wheel_building_kwargs(ireq): - download_dir = os.path.join(CACHE_DIR, "pkgs") - vistir.mkdir_p(download_dir) - - wheel_download_dir = os.path.join(CACHE_DIR, "wheels") - vistir.mkdir_p(wheel_download_dir) - - if ireq.source_dir is not None: - src_dir = ireq.source_dir - elif ireq.editable: - src_dir = _get_src_dir() - else: - src_dir = vistir.path.create_tracked_tempdir(prefix='passa-src') - - # This logic matches pip's behavior, although I don't fully understand the - # intention. I guess the idea is to build editables in-place, otherwise out - # of the source tree? - if ireq.editable: - build_dir = src_dir - else: - build_dir = vistir.path.create_tracked_tempdir(prefix="passa-build") - - return { - "build_dir": build_dir, - "src_dir": src_dir, - "download_dir": download_dir, - "wheel_download_dir": wheel_download_dir, - } - - -def _get_pip_index_urls(sources): - index_urls = [] - trusted_hosts = [] - for source in sources: - url = source.get("url") - if not url: - continue - index_urls.append(url) - if source.get("verify_ssl", True): - continue - host = six.moves.urllib.parse.urlparse(source["url"]).hostname - trusted_hosts.append(host) - return index_urls, trusted_hosts - - -class _PipCommand(pip_shims.Command): - name = "PipCommand" - - -def _get_pip_session(trusted_hosts): - cmd = _PipCommand() - options, _ = cmd.parser.parse_args([]) - options.cache_dir = CACHE_DIR - options.trusted_hosts = trusted_hosts - session = cmd._build_session(options) - return session - - -def _get_finder(sources): - index_urls, trusted_hosts = _get_pip_index_urls(sources) - session = _get_pip_session(trusted_hosts) - finder = pip_shims.PackageFinder( - find_links=[], - index_urls=index_urls, - trusted_hosts=trusted_hosts, - allow_all_prereleases=True, - session=session, - ) - return finder - - -def _get_wheel_cache(): - format_control = pip_shims.FormatControl(set(), set()) - wheel_cache = pip_shims.WheelCache(CACHE_DIR, format_control) - return wheel_cache - - -def _convert_hashes(values): - """Convert Pipfile.lock hash lines into InstallRequirement option format. - - The option format uses a str-list mapping. Keys are hash algorithms, and - the list contains all values of that algorithm. - """ - hashes = {} - if not values: - return hashes - for value in values: - try: - name, value = value.split(":", 1) - except ValueError: - name = "sha256" - if name not in hashes: - hashes[name] = [] - hashes[name].append(value) - return hashes - - -class WheelBuildError(RuntimeError): - pass - - -def build_wheel(ireq, sources, hashes=None): - """Build a wheel file for the InstallRequirement object. - - An artifact is downloaded (or read from cache). If the artifact is not a - wheel, build one out of it. The dynamically built wheel is ephemeral; do - not depend on its existence after the returned wheel goes out of scope. - - If `hashes` is truthy, it is assumed to be a list of hashes (as formatted - in Pipfile.lock) to be checked against the download. - - Returns a `distlib.wheel.Wheel` instance. Raises a `WheelBuildError` (a - `RuntimeError` subclass) if the wheel cannot be built. - """ - kwargs = _prepare_wheel_building_kwargs(ireq) - finder = _get_finder(sources) - - # Not for upgrade, hash not required. Hashes are not required here even - # when we provide them, because pip skips local wheel cache if we set it - # to True. Hashes are checked later if we need to download the file. - ireq.populate_link(finder, False, False) - - # Ensure ireq.source_dir is set. - # This is intentionally set to build_dir, not src_dir. Comments from pip: - # [...] if filesystem packages are not marked editable in a req, a non - # deterministic error occurs when the script attempts to unpack the - # build directory. - # Also see comments in `_prepare_wheel_building_kwargs()` -- If the ireq - # is editable, build_dir is actually src_dir, making the build in-place. - ireq.ensure_has_source_dir(kwargs["build_dir"]) - - # Ensure the source is fetched. For wheels, it is enough to just download - # because we'll use them directly. For an sdist, we need to unpack so we - # can build it. - if not ireq.editable or not pip_shims.is_file_url(ireq.link): - if ireq.is_wheel: - only_download = True - download_dir = kwargs["wheel_download_dir"] - else: - only_download = False - download_dir = kwargs["download_dir"] - ireq.options["hashes"] = _convert_hashes(hashes) - unpack_url( - ireq.link, ireq.source_dir, download_dir, - only_download=only_download, session=finder.session, - hashes=ireq.hashes(False), progress_bar="off", - ) - - if ireq.is_wheel: - # If this is a wheel, use the downloaded thing. - output_dir = kwargs["wheel_download_dir"] - wheel_path = os.path.join(output_dir, ireq.link.filename) - else: - # Othereise we need to build an ephemeral wheel. - wheel_path = _build_wheel( - ireq, vistir.path.create_tracked_tempdir(prefix="ephem"), - finder, _get_wheel_cache(), kwargs, - ) - if wheel_path is None or not os.path.exists(wheel_path): - raise WheelBuildError - return distlib.wheel.Wheel(wheel_path) - - -def _obtrain_ref(vcs_obj, src_dir, name, rev=None): - target_dir = os.path.join(src_dir, name) - target_rev = vcs_obj.make_rev_options(rev) - if not os.path.exists(target_dir): - vcs_obj.obtain(target_dir) - if (not vcs_obj.is_commit_id_equal(target_dir, rev) and - not vcs_obj.is_commit_id_equal(target_dir, target_rev)): - vcs_obj.update(target_dir, target_rev) - return vcs_obj.get_revision(target_dir) - - -def get_vcs_ref(requirement): - backend = VCS_SUPPORT.get_backend(requirement.vcs) - vcs = backend(url=requirement.req.vcs_uri) - src = _get_src_dir() - name = requirement.normalized_name - ref = _obtrain_ref(vcs, src, name, rev=requirement.req.ref) - return ref - - -def find_installation_candidates(ireq, sources): - finder = _get_finder(sources) - return finder.find_all_candidates(ireq.name) - - -class RequirementUninstaller(object): - """A context manager to remove a package for the inner block. - - This uses `UninstallPathSet` to control the workflow. If the inner block - exits correctly, the uninstallation is committed, otherwise rolled back. - """ - def __init__(self, ireq, auto_confirm, verbose): - self.ireq = ireq - self.pathset = None - self.auto_confirm = auto_confirm - self.verbose = verbose - - def __enter__(self): - self.pathset = self.ireq.uninstall( - auto_confirm=self.auto_confirm, - verbose=self.verbose, - ) - return self.pathset - - def __exit__(self, exc_type, exc_value, traceback): - if self.pathset is None: - return - if exc_type is None: - self.pathset.commit() - else: - self.pathset.rollback() - - -def uninstall(name, **kwargs): - ireq = pip_shims.InstallRequirement.from_line(name) - return RequirementUninstaller(ireq, **kwargs) - - -@contextlib.contextmanager -def _suppress_distutils_logs(): - """Hack to hide noise generated by `setup.py develop`. - - There isn't a good way to suppress them now, so let's monky-patch. - See https://bugs.python.org/issue25392. - """ - f = distutils.log.Log._log - - def _log(log, level, msg, args): - if level >= distutils.log.ERROR: - f(log, level, msg, args) - - distutils.log.Log._log = _log - yield - distutils.log.Log._log = f - - -class NoopInstaller(object): - """An installer. - - This class is not designed to be instantiated by itself, but used as a - common interface for subclassing. - - An installer has two methods, `prepare()` and `install()`. Neither takes - arguments, and should be called in that order to prepare an installation - operation, and to actually install things. - """ - def prepare(self): - pass - - def install(self): - pass - - -class EditableInstaller(NoopInstaller): - """Installer to handle editable. - """ - def __init__(self, requirement): - ireq = requirement.as_ireq() - self.working_directory = ireq.setup_py_dir - self.setup_py = ireq.setup_py - - def install(self): - with vistir.cd(self.working_directory), _suppress_distutils_logs(): - # Access from Setuptools to ensure things are patched correctly. - setuptools.dist.distutils.core.run_setup( - self.setup_py, ["develop", "--no-deps"], - ) - - -class WheelInstaller(NoopInstaller): - """Installer by building a wheel. - - The wheel is built during `prepare()`, and installed in `install()`. - """ - def __init__(self, requirement, sources, paths): - self.ireq = requirement.as_ireq() - self.sources = filter_sources(requirement, sources) - self.hashes = requirement.hashes or None - self.paths = paths - self.wheel = None - - def prepare(self): - self.wheel = build_wheel(self.ireq, self.sources, self.hashes) - - def install(self): - self.wheel.install(self.paths, distlib.scripts.ScriptMaker(None, None)) - - -def _iter_egg_info_directories(root, name): - name = packaging.utils.canonicalize_name(name) - for parent, dirnames, filenames in os.walk(root): - matched_indexes = [] - for i, dirname in enumerate(dirnames): - if not dirname.lower().endswith("egg-info"): - continue - egg_info_name = packaging.utils.canonicalize_name(dirname[:-9]) - if egg_info_name != name: - continue - matched_indexes.append(i) - yield os.path.join(parent, dirname) - - # Modify dirnames in-place to NOT look into egg-info directories. - # This is a documented behavior in stdlib. - for i in reversed(matched_indexes): - del dirnames[i] - - -def _read_pkg_info(directory): - path = os.path.join(directory, "PKG-INFO") - try: - with io.open(path, encoding="utf-8", errors="replace") as f: - return f.read() - except (IOError, OSError): - return None - - -def _find_egg_info(ireq): - """Find this package's .egg-info directory. - - Due to how sdists are designed, the .egg-info directory cannot be reliably - found without running setup.py to aggregate all configurations. This - function instead uses some heuristics to locate the egg-info directory - that most likely represents this package. - - The best .egg-info directory's path is returned as a string. None is - returned if no matches can be found. - """ - root = ireq.setup_py_dir - - directory_iterator = _iter_egg_info_directories(root, ireq.name) - try: - top_egg_info = next(directory_iterator) - except StopIteration: # No egg-info found. Wat. - return None - directory_iterator = itertools.chain([top_egg_info], directory_iterator) - - # Read the sdist's PKG-INFO to determine which egg_info is best. - pkg_info = _read_pkg_info(root) - - # PKG-INFO not readable. Just return whatever comes first, I guess. - if pkg_info is None: - return top_egg_info - - # Walk the sdist to find the egg-info with matching PKG-INFO. - for directory in directory_iterator: - egg_pkg_info = _read_pkg_info(directory) - if egg_pkg_info == pkg_info: - return directory - - # Nothing matches...? Use the first one we found, I guess. - return top_egg_info - - -def read_sdist_metadata(ireq): - egg_info_dir = _find_egg_info(ireq) - if not egg_info_dir: - return None - distribution = distlib.database.EggInfoDistribution(egg_info_dir) - return distribution.metadata diff --git a/src/passa/internals/_pip_shims.py b/src/passa/internals/_pip_shims.py deleted file mode 100644 index b2c7b6e..0000000 --- a/src/passa/internals/_pip_shims.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding=utf-8 -*- - -"""Shims to make the pip interface more consistent accross versions. - -There are currently two members: - -* VCS_SUPPORT is an instance of VcsSupport. -* build_wheel abstracts the process to build a wheel out of a bunch parameters. -* unpack_url wraps the actual function in pip to accept modern parameters. -""" - -from __future__ import absolute_import, unicode_literals - -import pip_shims - - -def _build_wheel_pre10(ireq, output_dir, finder, wheel_cache, kwargs): - kwargs.update({"wheel_cache": wheel_cache, "session": finder.session}) - reqset = pip_shims.RequirementSet(**kwargs) - builder = pip_shims.WheelBuilder(reqset, finder) - return builder._build_one(ireq, output_dir) - - -def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs): - """Build a wheel. - - * ireq: The InstallRequirement object to build - * output_dir: The directory to build the wheel in. - * finder: pip's internal Finder object to find the source out of ireq. - * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`. - """ - kwargs.update({"progress_bar": "off", "build_isolation": False}) - with pip_shims.RequirementTracker() as req_tracker: - if req_tracker: - kwargs["req_tracker"] = req_tracker - preparer = pip_shims.RequirementPreparer(**kwargs) - builder = pip_shims.WheelBuilder(finder, preparer, wheel_cache) - return builder._build_one(ireq, output_dir) - - -def _unpack_url_pre10(*args, **kwargs): - """Shim for unpack_url in various pip versions. - - pip before 10.0 does not accept `progress_bar` here. Simply drop it. - """ - kwargs.pop("progress_bar", None) - return pip_shims.unpack_url(*args, **kwargs) - - -PIP_VERSION = pip_shims.utils._parse(pip_shims.pip_version) -VERSION_10 = pip_shims.utils._parse("10") - - -VCS_SUPPORT = pip_shims.VcsSupport() - -build_wheel = _build_wheel_modern -unpack_url = pip_shims.unpack_url - -if PIP_VERSION < VERSION_10: - build_wheel = _build_wheel_pre10 - unpack_url = _unpack_url_pre10 diff --git a/src/passa/internals/candidates.py b/src/passa/internals/candidates.py index 67b0904..9076206 100644 --- a/src/passa/internals/candidates.py +++ b/src/passa/internals/candidates.py @@ -6,7 +6,8 @@ import packaging.version import requirementslib -from ._pip import find_installation_candidates, get_vcs_ref +from packagebuilder import find_installation_candidates +from ..models.caches import CACHE_DIR def _filter_matching_python_requirement(candidates, required_python): @@ -57,11 +58,11 @@ def find_candidates(requirement, sources, requires_python, allow_prereleases): if not requirement.is_named: candidate = _copy_requirement(requirement) if candidate.is_vcs: - candidate.req.ref = get_vcs_ref(candidate) + candidate.req.ref = requirement.get_commit_hash() return [candidate] ireq = requirement.as_ireq() - icans = find_installation_candidates(ireq, sources) + icans = find_installation_candidates(ireq, sources, cache_dir=CACHE_DIR) if requires_python: matching_icans = list(_filter_matching_python_requirement( diff --git a/src/passa/internals/dependencies.py b/src/passa/internals/dependencies.py index 1fa3b0b..e8c6d31 100644 --- a/src/passa/internals/dependencies.py +++ b/src/passa/internals/dependencies.py @@ -6,6 +6,7 @@ import os import sys +import packagebuilder import packaging.specifiers import packaging.utils import packaging.version @@ -13,8 +14,7 @@ import requirementslib import six -from ._pip import WheelBuildError, build_wheel, read_sdist_metadata -from .caches import DependencyCache, RequiresPythonCache +from ..models.caches import DependencyCache, RequiresPythonCache, CACHE_DIR from .markers import contains_extra, get_contained_extras, get_without_extra from .utils import get_pinned_version, is_pinned @@ -224,20 +224,10 @@ def _get_dependencies_from_pip(ireq, sources): 2. Read metadata out of the egg-info directory if it is present. """ extras = ireq.extras or () - try: - wheel = build_wheel(ireq, sources) - except WheelBuildError: - # XXX: This depends on a side effect of `build_wheel`. This block is - # reached when it fails to build an sdist, where the sdist would have - # been downloaded, extracted into `ireq.source_dir`, and partially - # built (hopefully containing .egg-info). - metadata = read_sdist_metadata(ireq) - if not metadata: - raise - else: - metadata = wheel.metadata - requirements = _read_requirements(metadata, extras) - requires_python = _read_requires_python(metadata) + builder = packagebuilder.BuiltDist(ireq, sources=sources, cache_dir=CACHE_DIR) + dist = builder.build() + requirements = _read_requirements(dist.metadata, extras) + requires_python = _read_requires_python(dist.metadata) return requirements, requires_python diff --git a/src/passa/internals/markers.py b/src/passa/internals/markers.py index 95efab9..3793e96 100644 --- a/src/passa/internals/markers.py +++ b/src/passa/internals/markers.py @@ -4,6 +4,17 @@ from packaging.markers import Marker +try: + from functools import lru_cache +except ImportError: + from backports.functools_lru_cache import lru_cache + + +def _ensure_marker(marker): + if not isinstance(marker, Marker): + return Marker(str(marker)) + return marker + def _strip_extra(elements): """Remove the "extra == ..." operands from the list. @@ -43,13 +54,10 @@ def get_without_extra(marker): This could return `None` if the `extra == ...` part is the only one in the input marker. """ - # TODO: Why is this very deep in the internals? Why is a better solution - # implementing it yourself when someone is already maintaining a codebase - # for this? It's literally a grammar implementation that is required to - # meet the demands of a pep... -d + if not marker: return None - marker = Marker(str(marker)) + marker = _ensure_marker(marker) elements = marker._markers _strip_extra(elements) if elements: @@ -68,6 +76,7 @@ def _markers_collect_extras(markers, collection): _markers_collect_extras(el, collection) +@lru_cache(maxsize=128) def get_contained_extras(marker): """Collect "extra == ..." operands from a marker. @@ -75,8 +84,8 @@ def get_contained_extras(marker): """ if not marker: return set() - marker = Marker(str(marker)) extras = set() + marker = _ensure_marker(marker) _markers_collect_extras(marker._markers, extras) return extras @@ -92,10 +101,11 @@ def _markers_contains_extra(markers): return False +@lru_cache(maxsize=128) def contains_extra(marker): """Check whehter a marker contains an "extra == ..." operand. """ if not marker: return False - marker = Marker(str(marker)) + marker = _ensure_marker(marker) return _markers_contains_extra(marker._markers) diff --git a/src/passa/internals/specifiers.py b/src/passa/internals/specifiers.py index 75afb6a..cf4c23e 100644 --- a/src/passa/internals/specifiers.py +++ b/src/passa/internals/specifiers.py @@ -2,17 +2,29 @@ from __future__ import absolute_import, unicode_literals +import collections import itertools import operator -from packaging.specifiers import SpecifierSet, Specifier +from cached_property import cached_property +from packaging.markers import Marker +from packaging.specifiers import Specifier, SpecifierSet + from vistir.misc import dedup +try: + from functools import lru_cache +except ImportError: + from backports.functools_lru_cache import lru_cache + + +@lru_cache(maxsize=128) def _tuplize_version(version): - return tuple(int(x) for x in version.split(".")) + return tuple(int(x) for x in filter(lambda i: i != "*", version.split("."))) +@lru_cache(maxsize=128) def _format_version(version): return ".".join(str(i) for i in version) @@ -21,18 +33,19 @@ def _format_version(version): REPLACE_RANGES = {">": ">=", "<=": "<"} +@lru_cache(maxsize=128) def _format_pyspec(specifier): if isinstance(specifier, str): if not any(op in specifier for op in Specifier._operators.keys()): specifier = "=={0}".format(specifier) specifier = Specifier(specifier) - if specifier.operator == "==" and specifier.version.endswith(".*"): - specifier = Specifier("=={0}".format(specifier.version[:-2])) + version = specifier.version.replace(".*", "") + if ".*" in specifier.version: + specifier = Specifier("{0}{1}".format(specifier.operator, version)) try: op = REPLACE_RANGES[specifier.operator] except KeyError: return specifier - version = specifier.version.replace(".*", "") curr_tuple = _tuplize_version(version) try: next_tuple = (curr_tuple[0], curr_tuple[1] + 1) @@ -42,17 +55,21 @@ def _format_pyspec(specifier): return specifier +@lru_cache(maxsize=128) def _get_specs(specset): + if specset is None: + return if isinstance(specset, Specifier): specset = str(specset) if isinstance(specset, str): specset = SpecifierSet(specset.replace(".*", "")) - return [ - (spec._spec[0], _tuplize_version(spec._spec[1])) - for spec in getattr(specset, "_specs", []) - ] + result = [] + for spec in set(specset): + result.append((spec.operator, _tuplize_version(spec.version))) + return result +@lru_cache(maxsize=128) def _group_by_op(specs): specs = [_get_specs(x) for x in list(specs)] flattened = [(op, version) for spec in specs for op, version in spec] @@ -61,12 +78,13 @@ def _group_by_op(specs): return grouping +@lru_cache(maxsize=128) def cleanup_pyspecs(specs, joiner="or"): specs = {_format_pyspec(spec) for spec in specs} # for != operator we want to group by version # if all are consecutive, join as a list results = set() - for op, versions in _group_by_op(specs): + for op, versions in _group_by_op(tuple(specs)): versions = [version[1] for version in versions] versions = sorted(dedup(versions)) # if we are doing an or operation, we need to use the min for >= @@ -113,6 +131,7 @@ def cleanup_pyspecs(specs, joiner="or"): return results +@lru_cache(maxsize=128) def pyspec_from_markers(marker): if marker._markers[0][0] != 'python_version': return @@ -134,3 +153,161 @@ def pyspec_from_markers(marker): if specset: return specset return None + + +class PySpecs(collections.abc.Set): + def __init__(self, specs=None): + if not specs: + specs = SpecifierSet() + self.specifierset = specs + self.previous_specifierset = None + self.cleaned_tuples = set() + self.markers = None + self.clean() + + def __key(self): + return tuple(sorted(self.specifierset, key=operator.attrgetter("_spec"))) + + def __contains__(self, other): + # The current specifierset fully has every value in the supplied specifierset + if not other.as_set - self.as_set: + return True + return False + + def __eq__(self, other): + return self.__key() == other.__key() + + def __hash__(self): + return hash(self.__key()) + + def __repr__(self): + return u"PySpecs({0!r})".format(str(self.specifierset)) + + def __len__(self): + return len(self.cleaned_tuples) + + def __iter__(self): + for version in self.as_string_set: + yield version + return + + def clean(self): + if len(set(self.specifierset)) == 1: + spec = next(iter(spec for spec in self.specifierset), None) + if spec: + self.cleaned_tuples.add((spec.operator, spec.version)) + else: + self.cleaned_tuples = cleanup_pyspecs(self.specifierset) + self.specifierset = self.as_specset + + def add(self, other): + new_pyspec = PySpecs(self.specifierset) + new_pyspec.specifierset &= other.specifierset + return new_pyspec + + @cached_property + @lru_cache(maxsize=128) + def as_specset(self): + specs = set() + for spec in self.cleaned_tuples: + op, value = spec + if op in ('in', 'not in'): + new_op = '!=' if op == 'not in' else '==' + for val in value.split(","): + specs.add(Specifier("{0}{1}".format(new_op, val))) + else: + specs.add(Specifier("{0}{1}".format(op, value))) + specifierset = SpecifierSet() + specifierset._specs = frozenset(specs) + return specifierset + + @cached_property + @lru_cache(maxsize=128) + def as_set(self): + return set(self.specifierset) + + @cached_property + @lru_cache(maxsize=128) + def as_string_set(self): + returnval = set() + if len(self.cleaned_tuples) == 1: + val = next(iter(spec for spec in self.cleaned_tuples), None) + if val: + returnval.add("python_version {0[0]} '{0[1]}'".format(val)) + return returnval + return set( + "python_version {0[0]} '{0[1]}'".format(s) + for s in sorted(self.cleaned_tuples) + ) + + @cached_property + @lru_cache(maxsize=128) + def marker_set(self): + markerset = {Marker(spec) for spec in self.as_string_set} + return markerset + + @cached_property + @lru_cache(maxsize=128) + def marker_string(self): + marker_string = " and ".join(sorted(str(m) for m in self.as_string_set)) + if not marker_string: + return "" + return marker_string + + @cached_property + @lru_cache(maxsize=128) + def as_markers(self): + if not self.marker_string: + return "" + marker = Marker(self.marker_string) + return marker + + @lru_cache(maxsize=128) + def __str__(self): + string_repr = u"{0}".format(str(self.marker_string)) + return string_repr + + def __bool__(self): + return bool(self.specifierset) + + def __nonzero__(self): # Python 2. + return self.__bool__() + + @lru_cache(maxsize=128) + def __or__(self, specset): + if not isinstance(specset, PySpecs): + specset = PySpecs(specset) + if str(self) == str(specset): + return self + combined_set = self.as_set | specset.as_set + new_specset = SpecifierSet() + new_specset._specs = frozenset(combined_set) + new_pyspec = PySpecs(new_specset) + return new_pyspec + + @classmethod + @lru_cache(maxsize=128) + def from_marker(cls, marker): + if marker._markers[0][0] != 'python_version': + return + op = marker._markers[0][1].value + version = marker._markers[0][2].value + specset = set() + if op == "in": + specset.update( + Specifier("=={0}".format(v.strip())) + for v in version.split(",") + ) + elif op == "not in": + specset.update( + Specifier("!={0}".format(v.strip())) + for v in version.split(",") + ) + else: + specset.add(Specifier("".join([op, version]))) + if specset: + specifierset = SpecifierSet() + specifierset._specs = frozenset(specset) + newset = cls(specifierset) + return newset + return None diff --git a/src/passa/internals/synchronizers.py b/src/passa/internals/synchronizers.py deleted file mode 100644 index 7ccce23..0000000 --- a/src/passa/internals/synchronizers.py +++ /dev/null @@ -1,214 +0,0 @@ -# -*- coding=utf-8 -*- - -from __future__ import absolute_import, unicode_literals - -import collections -import contextlib -import os -import sys -import sysconfig - -import pkg_resources - -import packaging.markers -import packaging.version -import requirementslib - -from ._pip import uninstall, EditableInstaller, WheelInstaller - - -def _is_installation_local(name): - """Check whether the distribution is in the current Python installation. - - This is used to distinguish packages seen by a virtual environment. A venv - may be able to see global packages, but we don't want to mess with them. - """ - loc = os.path.normcase(pkg_resources.working_set.by_key[name].location) - pre = os.path.normcase(sys.prefix) - return os.path.commonprefix([loc, pre]) == pre - - -def _is_up_to_date(distro, version): - # This is done in strings to avoid type mismatches caused by vendering. - return str(version) == str(packaging.version.parse(distro.version)) - - -GroupCollection = collections.namedtuple("GroupCollection", [ - "uptodate", "outdated", "noremove", "unneeded", -]) - - -def _group_installed_names(packages): - """Group locally installed packages based on given specifications. - - `packages` is a name-package mapping that are used as baseline to - determine how the installed package should be grouped. - - Returns a 3-tuple of disjoint sets, all containing names of installed - packages: - - * `uptodate`: These match the specifications. - * `outdated`: These installations are specified, but don't match the - specifications in `packages`. - * `unneeded`: These are installed, but not specified in `packages`. - """ - groupcoll = GroupCollection(set(), set(), set(), set()) - - for distro in pkg_resources.working_set: - name = distro.key - try: - package = packages[name] - except KeyError: - groupcoll.unneeded.add(name) - continue - - r = requirementslib.Requirement.from_pipfile(name, package) - if not r.is_named: - # Always mark non-named. I think pip does something similar? - groupcoll.outdated.add(name) - elif not _is_up_to_date(distro, r.get_version()): - groupcoll.outdated.add(name) - else: - groupcoll.uptodate.add(name) - - return groupcoll - - -@contextlib.contextmanager -def _remove_package(name): - if name is None or not _is_installation_local(name): - yield None - return - with uninstall(name, auto_confirm=True, verbose=False) as uninstaller: - yield uninstaller - - -def _get_packages(lockfile, default, develop): - # Don't need to worry about duplicates because only extras can differ. - # Extras don't matter because they only affect dependencies, and we - # don't install dependencies anyway! - packages = {} - if default: - packages.update(lockfile.default._data) - if develop: - packages.update(lockfile.develop._data) - return packages - - -def _build_paths(): - """Prepare paths for distlib.wheel.Wheel to install into. - """ - paths = sysconfig.get_paths() - return { - "prefix": sys.prefix, - "data": paths["data"], - "scripts": paths["scripts"], - "headers": paths["include"], - "purelib": paths["purelib"], - "platlib": paths["platlib"], - } - - -PROTECTED_FROM_CLEAN = {"setuptools", "pip", "wheel"} - - -def _clean(names): - cleaned = set() - for name in names: - if name in PROTECTED_FROM_CLEAN: - continue - with _remove_package(name) as uninst: - if uninst: - cleaned.add(name) - return cleaned - - -class Synchronizer(object): - """Helper class to install packages from a project's lock file. - """ - def __init__(self, project, default, develop, clean_unneeded): - self._root = project.root # Only for repr. - self.packages = _get_packages(project.lockfile, default, develop) - self.sources = project.lockfile.meta.sources._data - self.paths = _build_paths() - self.clean_unneeded = clean_unneeded - - def __repr__(self): - return "<{0} @ {1!r}>".format(type(self).__name__, self._root) - - def sync(self): - groupcoll = _group_installed_names(self.packages) - - installed = set() - updated = set() - cleaned = set() - - # TODO: Show a prompt to confirm cleaning. We will need to implement a - # reporter pattern for this as well. - if self.clean_unneeded: - names = _clean(groupcoll.unneeded) - cleaned.update(names) - - # TODO: Specify installation order? (pypa/pipenv#2274) - installers = [] - for name, package in self.packages.items(): - r = requirementslib.Requirement.from_pipfile(name, package) - name = r.normalized_name - if name in groupcoll.uptodate: - continue - markers = r.markers - if markers and not packaging.markers.Marker(markers).evaluate(): - continue - r.markers = None - if r.editable: - installer = EditableInstaller(r) - else: - installer = WheelInstaller(r, self.sources, self.paths) - try: - installer.prepare() - except Exception as e: - if os.environ.get("PASSA_NO_SUPPRESS_EXCEPTIONS"): - raise - print("failed to prepare {0!r}: {1}".format( - r.as_line(include_hashes=False), e, - )) - else: - installers.append((name, installer)) - - for name, installer in installers: - if name in groupcoll.outdated: - name_to_remove = name - else: - name_to_remove = None - try: - with _remove_package(name_to_remove): - installer.install() - except Exception as e: - if os.environ.get("PASSA_NO_SUPPRESS_EXCEPTIONS"): - raise - print("failed to install {0!r}: {1}".format( - r.as_line(include_hashes=False), e, - )) - continue - if name in groupcoll.outdated or name in groupcoll.noremove: - updated.add(name) - else: - installed.add(name) - - return installed, updated, cleaned - - -class Cleaner(object): - """Helper class to clean packages not in a project's lock file. - """ - def __init__(self, project, default, develop): - self._root = project.root # Only for repr. - self.packages = _get_packages(project.lockfile, default, develop) - - def __repr__(self): - return "<{0} @ {1!r}>".format(type(self).__name__, self._root) - - def clean(self): - groupcoll = _group_installed_names(self.packages) - cleaned = _clean(groupcoll.unneeded) - return cleaned diff --git a/src/passa/internals/utils.py b/src/passa/internals/utils.py index 8f8e6fd..0dd75d1 100644 --- a/src/passa/internals/utils.py +++ b/src/passa/internals/utils.py @@ -82,21 +82,6 @@ def is_pinned(ireq): return True -def filter_sources(requirement, sources): - """Returns a filtered list of sources for this requirement. - - This considers the index specified by the requirement, and returns only - matching source entries if there is at least one. - """ - if not sources or not requirement.index: - return sources - filtered_sources = [ - source for source in sources - if source.get("name") == requirement.index - ] - return filtered_sources or sources - - def get_allow_prereleases(requirement, global_setting): # TODO: Implement per-package prereleases flag. (pypa/pipenv#1696) return global_setting diff --git a/src/passa/models/__init__.py b/src/passa/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/passa/internals/caches.py b/src/passa/models/caches.py similarity index 98% rename from src/passa/internals/caches.py rename to src/passa/models/caches.py index 6d3131f..bda8cc2 100644 --- a/src/passa/internals/caches.py +++ b/src/passa/models/caches.py @@ -13,12 +13,13 @@ import requests import vistir -from ._pip_shims import VCS_SUPPORT -from .utils import get_pinned_version +from ..internals.utils import get_pinned_version CACHE_DIR = os.environ.get("PASSA_CACHE_DIR", appdirs.user_cache_dir("passa")) +VCS_SUPPORT = pip_shims.VcsSupport() + class HashCache(pip_shims.SafeFileCache): """Caches hashes of PyPI artifacts so we do not need to re-download them. diff --git a/src/passa/internals/lockers.py b/src/passa/models/lockers.py similarity index 95% rename from src/passa/internals/lockers.py rename to src/passa/models/lockers.py index b567c46..53f1cab 100644 --- a/src/passa/internals/lockers.py +++ b/src/passa/models/lockers.py @@ -4,18 +4,19 @@ import itertools +import resolvelib + import plette import requirementslib -import resolvelib import vistir +from ..internals.hashes import get_hashes +from ..internals.reporters import StdOutReporter +from ..internals.traces import trace_graph +from ..internals.utils import identify_requirment from .caches import HashCache -from .hashes import get_hashes from .metadata import set_metadata from .providers import BasicProvider, EagerUpgradeProvider, PinReuseProvider -from .reporters import StdOutReporter -from .traces import trace_graph -from .utils import identify_requirment def _get_requirements(model, section_name): @@ -70,6 +71,9 @@ def _collect_derived_entries(state, traces, identifiers): extras[name].extend(requirement.extras) except KeyError: extras[name] = list(requirement.extras) + if requirement.editable and requirement.markers: + requirement.markers = set() + requirement.req.req.markers = set() entries[name] = next(iter(requirement.as_pipfile().values())) for name, ext in extras.items(): entries[name]["extras"] = ext diff --git a/src/passa/internals/metadata.py b/src/passa/models/metadata.py similarity index 75% rename from src/passa/internals/metadata.py rename to src/passa/models/metadata.py index 9709c53..e626678 100644 --- a/src/passa/internals/metadata.py +++ b/src/passa/models/metadata.py @@ -10,8 +10,8 @@ import vistir import vistir.misc -from .markers import get_without_extra -from .specifiers import cleanup_pyspecs, pyspec_from_markers +from ..internals.markers import get_without_extra +from ..internals.specifiers import PySpecs def dedup_markers(s): @@ -28,24 +28,39 @@ class MetaSet(object): """ def __init__(self): self.markerset = frozenset() - self.pyspecset = packaging.specifiers.SpecifierSet() + self.pyspecset = PySpecs() def __repr__(self): return "MetaSet(markerset={0!r}, pyspecset={1!r})".format( ",".join(sorted(self.markerset)), str(self.pyspecset), ) + def __key(self): + return (tuple(self.markerset), hash(self.pyspecset)) + + def __hash__(self): + return hash(self.__key()) + + def __eq__(self, other): + return self.__key() == other.__key() + + def __len__(self): + return len(self.markerset) + len(self.pyspecset) + + def __iter__(self): + return itertools.chain(self.markerset, self.pyspecset) + def __str__(self): - pyspecs = set() + pyspecs = PySpecs() markerset = set() for m in self.markerset: - marker_specs = pyspec_from_markers(packaging.markers.Marker(m)) + marker_specs = PySpecs.from_marker(packaging.markers.Marker(m)) if marker_specs: pyspecs.add(marker_specs) else: markerset.add(m) if pyspecs: - self.pyspecset._specs &= pyspecs + self.pyspecset.add(pyspecs) self.markerset = frozenset(markerset) return " and ".join(dedup_markers(itertools.chain( # Make sure to always use the same quotes so we can dedup properly. @@ -54,8 +69,7 @@ def __str__(self): for ms in (str(m).replace('"', "'") for m in self.markerset) ), ( - "python_version {0[0]} '{0[1]}'".format(spec) - for spec in cleanup_pyspecs(self.pyspecset) + "{0}".format(str(spec)) for spec in self.pyspecset ), ))) @@ -68,16 +82,17 @@ def __nonzero__(self): # Python 2. def __or__(self, pair): marker, specset = pair markerset = set(self.markerset) + specset = PySpecs(specset) if marker: - marker_specs = pyspec_from_markers(marker) + marker_specs = PySpecs.from_marker(marker) if not marker_specs: markerset.add(str(marker)) else: - specset._specs &= marker_specs + specset.add(marker_specs) metaset = MetaSet() metaset.markerset = frozenset(markerset) # TODO: Implement some logic to clean up dups like '3.0.*' and '3.0'. - metaset.pyspecset &= self.pyspecset & specset + metaset.pyspecset = self.pyspecset | specset return metaset @@ -91,19 +106,19 @@ def _build_metasets(dependencies, pythons, key, trace, all_metasets): return all_parent_metasets.append((parent, parent_metasets)) - metaset_iters = [] + metasets = set() for parent, parent_metasets in all_parent_metasets: r = dependencies[parent][key] python = pythons[key] + markers = None if r.editable else get_without_extra(r.markers) metaset = ( - get_without_extra(r.markers), + markers, packaging.specifiers.SpecifierSet(python), ) - metaset_iters.append( - parent_metaset | metaset - for parent_metaset in parent_metasets - ) - return list(itertools.chain.from_iterable(metaset_iters)) + for parent_metaset in parent_metasets: + child_metaset = parent_metaset | metaset + metasets.add(child_metaset) + return list(metasets) def _calculate_metasets_mapping(dependencies, pythons, traces): @@ -117,7 +132,7 @@ def _calculate_metasets_mapping(dependencies, pythons, traces): metasets = _build_metasets( dependencies, pythons, key, trace, all_metasets, ) - if metasets is None: + if metasets is None or len(metasets) == 0: continue new_metasets[key] = metasets if not new_metasets: @@ -135,11 +150,11 @@ def _format_metasets(metasets): return None # This extra str(Marker()) call helps simplify the expression. - return str(packaging.markers.Marker(" or ".join( - "{0}".format(s) if " and " in s else s - for s in dedup_markers(str(metaset) for metaset in metasets - if metaset) - ))) + _metasets = (dedup_markers(str(metaset) for metaset in metasets if metaset)) + metaset_string = " or ".join(meta for meta in list(_metasets)) + if not metaset_string: + return metaset_string + return str(packaging.markers.Marker(metaset_string)) def set_metadata(candidates, traces, dependencies, pythons): diff --git a/src/passa/internals/projects.py b/src/passa/models/projects.py similarity index 99% rename from src/passa/internals/projects.py rename to src/passa/models/projects.py index f6e037d..7ff6f31 100644 --- a/src/passa/internals/projects.py +++ b/src/passa/models/projects.py @@ -84,6 +84,7 @@ def dumps(self): class Project(object): root = attr.ib() + env_prefix = attr.ib(default=None) _p = attr.ib(init=False) _l = attr.ib(init=False) diff --git a/src/passa/internals/providers.py b/src/passa/models/providers.py similarity index 97% rename from src/passa/internals/providers.py rename to src/passa/models/providers.py index bf4fd22..e62a031 100644 --- a/src/passa/internals/providers.py +++ b/src/passa/models/providers.py @@ -6,11 +6,12 @@ import resolvelib -from .candidates import find_candidates -from .dependencies import get_dependencies -from .utils import ( - filter_sources, get_allow_prereleases, - are_requirements_equal, identify_requirment, strip_extras, +from packagebuilder import filter_sources + +from ..internals.candidates import find_candidates +from ..internals.dependencies import get_dependencies +from ..internals.utils import ( + get_allow_prereleases, identify_requirment, strip_extras, ) diff --git a/src/passa/operations/sync.py b/src/passa/operations/sync.py deleted file mode 100644 index 3014e8d..0000000 --- a/src/passa/operations/sync.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding=utf-8 -*- - -from __future__ import absolute_import, print_function, unicode_literals - - -def sync(syncer): - print("Starting synchronization") - installed, updated, cleaned = syncer.sync() - if cleaned: - print("Uninstalled: {}".format(", ".join(sorted(cleaned)))) - if installed: - print("Installed: {}".format(", ".join(sorted(installed)))) - if updated: - print("Updated: {}".format(", ".join(sorted(updated)))) - return True - - -def clean(cleaner): - print("Cleaning") - cleaned = cleaner.clean() - if cleaned: - print("Uninstalled: {}".format(", ".join(sorted(cleaned)))) - return True diff --git a/tasks/package.py b/tasks/package.py index f229e3a..5ae379b 100644 --- a/tasks/package.py +++ b/tasks/package.py @@ -5,7 +5,8 @@ import distlib.scripts import distlib.wheel import invoke -import passa.internals._pip +import packagebuilder +import passa.models.caches import plette import requirementslib @@ -75,8 +76,8 @@ def pack(ctx, remove_lib=True): package.pop('editable', None) # Don't install things as editable. package.pop('markers', None) # Always install everything. r = requirementslib.Requirement.from_pipfile(name, package) - wheel = passa.internals._pip.build_wheel( - r.as_ireq(), sources, r.hashes or None, + wheel = packagebuilder._pip.build_wheel( + r.as_ireq(), sources, r.hashes or None, cache_dir=passa.models.caches.CACHE_DIR ) wheel.install(paths, maker, lib_only=True) diff --git a/tests/actions/__init__.py b/tests/actions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/actions/test_add.py b/tests/actions/test_add.py new file mode 100644 index 0000000..e7cd883 --- /dev/null +++ b/tests/actions/test_add.py @@ -0,0 +1,20 @@ +# -*- coding=utf-8 -*- +import passa.actions.init +import passa.actions.add +import passa.cli.options +import passa.models.projects + + +def test_add_one(project_directory): + project = passa.cli.options.Project(project_directory.strpath) + retcode = passa.actions.add.add_packages(["pytz"], project=project) + assert not retcode + assert 'pytz' in project.lockfile.default + + +def test_add_one_with_deps(project_directory): + project = passa.cli.options.Project(project_directory.strpath) + retcode = passa.actions.add.add_packages(["requests"], project=project) + assert not retcode + assert 'requests' in project.lockfile.default + assert 'idna' in project.lockfile.default diff --git a/tests/actions/test_clean.py b/tests/actions/test_clean.py new file mode 100644 index 0000000..c56d06d --- /dev/null +++ b/tests/actions/test_clean.py @@ -0,0 +1,18 @@ +# -*- coding=utf-8 -*- +import passa.actions.add +import passa.actions.clean + + +def test_clean_subset(project): + retcode = passa.actions.add.add_packages(["requests"], project=project) + assert not retcode + packages = ["requests", "chardet", "certifi", "idna"] + c = project.venv.run("pip install pytz") + assert c.returncode == 0 + c = project.venv.run("python -c 'import pytz'") + assert c.returncode == 0 + clean_retcode = passa.actions.clean.clean(project=project) + assert not clean_retcode + c = project.venv.run("python -c 'import pytz'") + assert c.returncode != 0 + assert all(pkg in project.lockfile.default for pkg in packages) diff --git a/tests/actions/test_freeze.py b/tests/actions/test_freeze.py new file mode 100644 index 0000000..53d34f9 --- /dev/null +++ b/tests/actions/test_freeze.py @@ -0,0 +1,21 @@ +# -*- coding=utf-8 -*- +import passa.actions.add +import passa.actions.freeze +import passa.cli.options +import passa.models.projects + + +def test_freeze(project_directory): + project = passa.cli.options.Project(project_directory.strpath) + retcode = passa.actions.add.add_packages(["requests"], project=project) + assert not retcode + packages = ["requests", "chardet", "certifi", "idna"] + assert all(pkg in project.lockfile.default for pkg in packages) + freeze_file = project_directory.join("requirements.txt") + freeze_retcode = passa.actions.freeze.freeze( + project=project, include_hashes=False, target=freeze_file.strpath + ) + assert not freeze_retcode + lines = [line.strip() for line in freeze_file.readlines() if line.strip() != ''] + for pkg in packages: + assert any(line.startswith(pkg) for line in lines) diff --git a/tests/actions/test_init.py b/tests/actions/test_init.py new file mode 100644 index 0000000..2f12530 --- /dev/null +++ b/tests/actions/test_init.py @@ -0,0 +1,19 @@ +# -*- coding=utf-8 -*- + +import pytest + +import passa.actions.init +import passa.cli.options + + +def test_init(tmpdir): + init_retcode = passa.actions.init.init_project(root=tmpdir.strpath) + assert init_retcode == 0 + project = passa.cli.options.Project(tmpdir.strpath) + assert project.pipfile.packages._data == {} + assert project.pipfile.dev_packages._data == {} + + +def test_init_exists(project_directory): + with pytest.raises(RuntimeError, match=r'.* is already a Pipfile project'): + passa.actions.init.init_project(root=project_directory.strpath) diff --git a/tests/actions/test_install.py b/tests/actions/test_install.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/actions/test_lock.py b/tests/actions/test_lock.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/actions/test_remove.py b/tests/actions/test_remove.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/actions/test_sync.py b/tests/actions/test_sync.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/actions/test_upgrade.py b/tests/actions/test_upgrade.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/__init__.py b/tests/cli/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/test_add.py b/tests/cli/test_add.py new file mode 100644 index 0000000..a6bcbda --- /dev/null +++ b/tests/cli/test_add.py @@ -0,0 +1 @@ +# -*- coding=utf-8 -*- diff --git a/tests/cli/test_clean.py b/tests/cli/test_clean.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/test_freeze.py b/tests/cli/test_freeze.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/test_init.py b/tests/cli/test_init.py new file mode 100644 index 0000000..a6bcbda --- /dev/null +++ b/tests/cli/test_init.py @@ -0,0 +1 @@ +# -*- coding=utf-8 -*- diff --git a/tests/cli/test_install.py b/tests/cli/test_install.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/test_lock.py b/tests/cli/test_lock.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/test_remove.py b/tests/cli/test_remove.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/test_sync.py b/tests/cli/test_sync.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/test_upgrade.py b/tests/cli/test_upgrade.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..1aaf419 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,61 @@ +# -*- coding=utf-8 -*- +import os +import pytest +import passa +import passa.cli.options +import mork.virtualenv +import sys +import vistir + + +DEFAULT_PIPFILE_CONTENTS = """ +[[source]] +name = "pypi" +url = "https://pypi.org/simple" +verify_ssl = true + +[packages] + +[dev-packages] +""".strip() + + +@pytest.fixture(scope="function") +def project_directory(tmpdir_factory): + project_dir = tmpdir_factory.mktemp("passa-project") + project_dir.join("Pipfile").write(DEFAULT_PIPFILE_CONTENTS) + with vistir.contextmanagers.cd(project_dir.strpath): + yield project_dir + + +@pytest.fixture(scope="function") +def virtualenv(tmpdir_factory): + venv_dir = tmpdir_factory.mktemp("passa-testenv") + print("Creating virtualenv {0!r}".format(venv_dir.strpath)) + c = vistir.misc.run([sys.executable, "-m", "virtualenv", venv_dir.strpath], + return_object=True, block=True, nospin=True) + if c.returncode == 0: + print("Virtualenv created...") + return venv_dir + raise RuntimeError("Failed creating virtualenv for testing...{0!r}".format(c.err.strip())) + + +class _Project(passa.cli.options.Project): + def __init__(self, root, venv=None): + self.path = root.strpath + self.venv = venv + super(_Project, self).__init__(self.path) + + +@pytest.fixture +def tmpvenv(virtualenv): + return mork.virtualenv.VirtualEnv(virtualenv.strpath) + + +@pytest.fixture(scope="function") +def project(project_directory, tmpvenv): + venv_working_set = tmpvenv.initial_working_set + passa_dist = venv_working_set.by_key["passa"] + resolved = tmpvenv.resolve_dist(passa_dist, venv_working_set) + with tmpvenv.activated(extra_dists=list(resolved)): + yield _Project(project_directory, tmpvenv) diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tox.ini b/tox.ini index 2bc8e1d..52124e8 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ setenv = LC_ALL = en_US.UTF-8 deps = coverage - -e .[tests] + -e .[virtualenv,tests] commands = coverage run --parallel -m pytest --timeout 300 [] install_command = python -m pip install {opts} {packages} usedevelop = True