Repository: nosarthur/gita

Issue:
Command for mass-clone
Hi,

thank you so much for gita, it's a very nice tool.

The one thing I'm missing is a "clone" command. I'd like to have a list of URLs in the config file of gita, together with the location it should clone them on the filesystem. This would allow me to do a 'gita clone' which then would clone all these repositories (if not already existing).

Use-case: when re-installing a system, a 'gita clone' would be enough to be ready again.

Regards,
Daniel

Comments:

Patch:
diff --git a/gita/__main__.py b/gita/__main__.py
index 8d08742..9e4871c 100644
--- a/gita/__main__.py
+++ b/gita/__main__.py
@@ -72,6 +72,23 @@ def f_info(args: argparse.Namespace):
               yaml.dump(to_display, f, default_flow_style=None)
 
 
+def f_clone(args: argparse.Namespace):
+    path = Path.cwd()
+    errors = utils.exec_async_tasks(
+            utils.run_async(repo_name, path, ['git', 'clone', url])
+            for url, repo_name, _ in utils.parse_clone_config(args.fname))
+
+
+def f_freeze(_):
+    repos = utils.get_repos()
+    for name, path in repos.items():
+        url = ''
+        cp = subprocess.run(['git', 'remote', '-v'], cwd=path, capture_output=True)
+        if cp.returncode == 0:
+            url = cp.stdout.decode('utf-8').split('\n')[0].split()[1]
+        print(f'{url},{name},{path}')
+
+
 def f_ll(args: argparse.Namespace):
     """
     Display details of all repos
@@ -238,15 +255,21 @@ def main(argv=None):
                       help="remove the chosen repo(s)")
     p_rm.set_defaults(func=f_rm)
 
+    p_freeze = subparsers.add_parser('freeze', help='print all repo information')
+    p_freeze.set_defaults(func=f_freeze)
+
+    p_clone = subparsers.add_parser('clone', help='clone repos from config file')
+    p_clone.add_argument('fname',
+            help='config file. Its content should be the output of `gita freeze`.')
+    p_clone.set_defaults(func=f_clone)
+
     p_rename = subparsers.add_parser('rename', help='rename a repo')
     p_rename.add_argument(
         'repo',
         nargs=1,
         choices=utils.get_repos(),
         help="rename the chosen repo")
-    p_rename.add_argument(
-        'new_name',
-        help="new name")
+    p_rename.add_argument('new_name', help="new name")
     p_rename.set_defaults(func=f_rename)
 
     p_color = subparsers.add_parser('color',
diff --git a/gita/utils.py b/gita/utils.py
index d30a82e..06cdf07 100644
--- a/gita/utils.py
+++ b/gita/utils.py
@@ -4,7 +4,7 @@ import asyncio
 import platform
 from functools import lru_cache, partial
 from pathlib import Path
-from typing import List, Dict, Coroutine, Union
+from typing import List, Dict, Coroutine, Union, Iterator
 
 from . import info
 from . import common
@@ -128,6 +128,8 @@ def write_to_groups_file(groups: Dict[str, List[str]], mode: str):
 def add_repos(repos: Dict[str, str], new_paths: List[str]):
     """
     Write new repo paths to file
+
+    @param repos: name -> path
     """
     existing_paths = set(repos.values())
     new_paths = set(os.path.abspath(p) for p in new_paths if is_git(p))
@@ -142,6 +144,15 @@ def add_repos(repos: Dict[str, str], new_paths: List[str]):
         print('No new repos found!')
 
 
+def parse_clone_config(fname: str) -> Iterator[List[str]]:
+    """
+    Return the url, name, and path of all repos in `fname`.
+    """
+    with open(fname) as f:
+        for line in f:
+            yield line.strip().split(',')
+
+
 async def run_async(repo_name: str, path: str, cmds: List[str]) -> Union[None, str]:
     """
     Run `cmds` asynchronously in `path` directory. Return the `path` if
diff --git a/setup.py b/setup.py
index 1c6ebd0..bfaaa01 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ with open('README.md', encoding='utf-8') as f:
 setup(
     name='gita',
     packages=['gita'],
-    version='0.12.2',
+    version='0.12.3',
     license='MIT',
     description='Manage multiple git repos with sanity',
     long_description=long_description,


Test patch:
diff --git a/tests/test_main.py b/tests/test_main.py
index e90050d..ecb13fe 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -95,6 +95,16 @@ class TestLsLl:
         assert out == expected
 
 
+@patch('subprocess.run')
+@patch('gita.utils.get_repos', return_value={'repo1': '/a/', 'repo2': '/b/'})
+def test_freeze(_, mock_run, capfd):
+    __main__.main(['freeze'])
+    assert mock_run.call_count == 2
+    out, err = capfd.readouterr()
+    assert err == ''
+    assert out == ',repo1,/a/\n,repo2,/b/\n'
+
+
 @patch('os.path.isfile', return_value=True)
 @patch('gita.common.get_config_fname', return_value='some path')
 @patch('gita.utils.get_repos', return_value={'repo1': '/a/', 'repo2': '/b/'})