Advertisement
Danila_lipatov

Copy_repos

Aug 8th, 2022 (edited)
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.06 KB | None | 0 0
  1. import gitlab
  2. import shutil
  3. import subprocess
  4. import pathlib
  5. import warnings
  6. import contextlib
  7. from datetime import datetime as dt
  8. import datetime, time
  9. import requests
  10. from urllib3.exceptions import InsecureRequestWarning
  11. import pandas as pd
  12.  
  13. old_merge_environment_settings = requests.Session.merge_environment_settings
  14.  
  15.  
  16. @contextlib.contextmanager
  17. def no_ssl_verification():
  18.     opened_adapters = set()
  19.  
  20.     def merge_environment_settings(self, url, proxies, stream, verify, cert):
  21.         # Verification happens only once per connection so we need to close
  22.         # all the opened adapters once we're done. Otherwise, the effects of
  23.         # verify=False persist beyond the end of this context manager.
  24.         opened_adapters.add(self.get_adapter(url))
  25.  
  26.         settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
  27.         settings['verify'] = False
  28.  
  29.         return settings
  30.  
  31.     requests.Session.merge_environment_settings = merge_environment_settings
  32.  
  33.     try:
  34.         with warnings.catch_warnings():
  35.             warnings.simplefilter('ignore', InsecureRequestWarning)
  36.             yield
  37.     finally:
  38.         requests.Session.merge_environment_settings = old_merge_environment_settings
  39.  
  40.         for adapter in opened_adapters:
  41.             try:
  42.                 adapter.close()
  43.             except:
  44.                 pass
  45.  
  46.  
  47. def delete_folders(dir_path, hours, fn):
  48.     if fn == "":
  49.         fn = today.strftime("%m-%d-%Y0-%H-%M")
  50.     hours = datetime.timedelta(hours=hours)     #converting
  51.     for path in dir_path:
  52.         if dt.strptime(fn, "%m-%d-%Y0-%H-%M") - dt.strptime(path, "%m-%d-%Y0-%H-%M") > hours:
  53.             shutil.rmtree(f"C:/tmp/{path}")                 #remove recursivaly dir
  54.             #pathlib.Path(f"C:/tmp/{path}/").unlink()       remove only specific file
  55.             #pathlib.Path(f"C:/tmp/{path}").rmdir()         remove only empty dir
  56.  
  57.  
  58. # https://stackoverflow.com/questions/15445981/how-do-i-disable-the-security-certificate-check-in-python-requests
  59.  
  60. # https://code-maven.com/slides/gitlab/gitlab-api-using-python
  61. # https://www.cyberforum.ru/python/thread1723215.html
  62. # https://python-gitlab.readthedocs.io/en/stable/gl_objects/projects.html
  63.  
  64.  
  65. all_dir_path = []
  66. for path in pathlib.Path('C:/tmp').iterdir():
  67.     all_dir_path.append(pathlib.PurePosixPath(path).name)
  68.     # print(parent.path)                             #todo check all folders
  69.  
  70. today = dt.now()
  71.  
  72. p = pathlib.Path("C:/tmp").resolve()
  73. fn = today.strftime("%m-%d-%Y0-%H-%M")
  74. # temppath = str(p / fn).replace('\\', '/')
  75. print(fn)
  76. delete_folders(all_dir_path, 72, "")
  77. temppath = p / fn
  78. path = pathlib.Path(temppath)
  79. path.mkdir(parents=True, exist_ok=True)
  80. check = path / "out.csv"  # for save csv files
  81. print(path)
  82. full_projects = []
  83. namewithspace = []
  84. rep = []
  85. created_at = []
  86. last_activity_at = []
  87. count_is = []
  88. df = pd.DataFrame()
  89. projects = {}
  90.  
  91. with no_ssl_verification():
  92.     gl = gitlab.Gitlab(url= 'ur url', private_token='ur token')
  93.     gl.auth()
  94.     groups = gl.groups.list()
  95.     for x in groups:
  96.         full_projects.append(x.name)
  97.     for i, values in enumerate(gl.projects.list(iterator=True)):
  98.         # if i>0: continue
  99.         # pd.DataFrame.from_dict(values.attributes, orient='index').to_excel('1.xlsx')
  100.         print(values.attributes)
  101.         if values.namespace['name'] in full_projects:
  102.             namewithspace.append(values.namespace['name'])
  103.             rep.append(values.name)
  104.             created_at.append(values.created_at)
  105.             last_activity_at.append(values.last_activity_at)
  106.             count_is.append(values.open_issues_count)
  107.             print(values.namespace['name'], values.name, values.default_branch, sep=" ")
  108.             # print(values.name)     #TODO this or full path(including group.name)
  109.             # print(values.default_branch)  # TODO check differences between .name & .path
  110.             # print(values.issues)                       #TODO count them
  111.     # df = pd.concat([pd.DataFrame(group),pd.DataFrame(rep),pd.DataFrame(branch), pd.DataFrame(count_is)], axis= 1)  #todo check this constrution
  112.     df['group'] = pd.DataFrame(namewithspace)
  113.     df['repo'] = pd.DataFrame(rep)
  114.     df['created_at'] = pd.DataFrame(created_at)
  115.     df['last_activity_at'] = pd.DataFrame(last_activity_at)
  116.     df['count_issues'] = pd.DataFrame(count_is)
  117.     print(df)
  118.     df.to_csv(check)
  119.     # groupname = "validation"        #or could be massive
  120.     for group in groups:
  121.         # if group.name == groupname:        add if it isn't necessary to clone all groups
  122.         projects[group] = group.projects.list(all=True)
  123.         # projects = group.projects.list(all=True)
  124.         print(projects)
  125.  
  126.     for group, repos in projects.items():
  127.         for repo in repos:
  128.             if repo.name == 'ttttttttt': continue
  129.             command = f'git clone {repo.ssh_url_to_repo}'
  130.             process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True,
  131.                                        cwd=f"{path}")  # your path
  132.             output, _ = process.communicate()
  133.             process.wait()
  134.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement