cargo-outdated 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. #!/usr/bin/env python3.9
  2. import json
  3. import pickle
  4. import subprocess
  5. from argparse import ArgumentParser
  6. from os import getenv
  7. from os.path import exists, join
  8. from subprocess import PIPE
  9. import semver
  10. import toml
  11. from colorama import Fore, Style
  12. from prettytable import PrettyTable
  13. # Path to git repository holding crates.io index
  14. CRATESIO_REPO = "https://github.com/rust-lang/crates.io-index"
  15. CRATESIO_INDEX = join(getenv("HOME"), ".cache", "crates.io-index")
  16. # Path to pickle cache for storing paths to dependency metadata
  17. PICKLE_CACHE = join(getenv("HOME"), ".cache", "cargo-outdated.pickle")
  18. # Set of packages that are ignored by this tool
  19. IGNORES = {"drk-sdk", "darkfi", "darkfi-derive", "darkfi-derive-internal"}
  20. # Cached paths for metadata to not have to search through the crates index
  21. METADATA_PATHS = {}
  22. if exists(PICKLE_CACHE):
  23. with open(PICKLE_CACHE, "rb") as f:
  24. json_data = pickle.load(f)
  25. METADATA_PATHS = json.loads(json_data)
  26. def parse_toml(file):
  27. with open(file) as f:
  28. content = f.read()
  29. p = toml.loads(content)
  30. deps = p.get("dependencies")
  31. devdeps = p.get("dev-dependencies")
  32. if deps and devdeps:
  33. dependencies = deps | devdeps
  34. elif deps:
  35. dependencies = deps
  36. elif devdeps:
  37. dependencies = devdeps
  38. else:
  39. dependencies = None
  40. return (p["package"]["name"], dependencies)
  41. def get_metadata_path(name):
  42. find_output = subprocess.run(
  43. ["find", CRATESIO_INDEX, "-type", "f", "-name", name], stdout=PIPE)
  44. metadata_path = find_output.stdout.decode().strip()
  45. if metadata_path == '':
  46. return None
  47. # Place the path into cache
  48. METADATA_PATHS[name] = metadata_path
  49. return metadata_path
  50. def check_dep(name, data):
  51. if name in IGNORES:
  52. return None
  53. metadata_path = METADATA_PATHS.get(name)
  54. if not metadata_path:
  55. metadata_path = get_metadata_path(name)
  56. if not metadata_path:
  57. print(f"No crate found for {Fore.YELLOW}{name}{Style.RESET_ALL}")
  58. return None
  59. # Read the metadata. It's split as JSON objects, each in its own line.
  60. with open(metadata_path, encoding="utf-8") as f:
  61. lines = f.readlines()
  62. lines = [i.strip() for i in lines]
  63. # Latest one is at the end
  64. metadata = json.loads(lines[-1])
  65. # Get the version from the local data
  66. if isinstance(data, str):
  67. # This is just the semver
  68. local_version = data
  69. elif isinstance(data, dict):
  70. local_version = data.get("version")
  71. if not local_version:
  72. # Not a versioned dependency (can be path/git/...)
  73. return None
  74. else:
  75. raise ValueError(f"Invalid dependency: {name}")
  76. if semver.compare(local_version, metadata["vers"], loose=True) < 0:
  77. return (local_version, metadata["vers"])
  78. return None
  79. def main():
  80. parser = ArgumentParser(
  81. description="Prettyprint outdated dependencies in a cargo project")
  82. parser.add_argument("-i",
  83. "--ignore",
  84. type=str,
  85. help="Comma-separated list of deps to ignore")
  86. args = parser.parse_args()
  87. if args.ignore:
  88. for i in args.ignore.split(","):
  89. IGNORES.add(i)
  90. if not exists(CRATESIO_INDEX):
  91. print("Cloning crates.io index...")
  92. subprocess.run(["git", "clone", CRATESIO_REPO, CRATESIO_INDEX],
  93. capture_output=False)
  94. print("Updating crates.io index...")
  95. subprocess.run(["git", "-C", CRATESIO_INDEX, "fetch", "-a"],
  96. capture_output=False)
  97. subprocess.run(
  98. ["git", "-C", CRATESIO_INDEX, "reset", "--hard", "origin/master"],
  99. capture_output=False)
  100. find_output = subprocess.run(
  101. ["find", ".", "-type", "f", "-name", "Cargo.toml"], stdout=PIPE)
  102. files = [i.strip() for i in find_output.stdout.decode().split("\n")][:-1]
  103. x = PrettyTable()
  104. x.field_names = ["package", "crate", "current", "latest", "path"]
  105. for file in files:
  106. package, deps = parse_toml(file)
  107. parse_toml(file)
  108. print(f"Checking deps for {Fore.GREEN}{package}{Style.RESET_ALL}")
  109. for dep in deps:
  110. ret = check_dep(dep, deps[dep])
  111. if ret:
  112. x.add_row([
  113. package,
  114. dep,
  115. f"{Fore.YELLOW}{ret[0]}{Style.RESET_ALL}",
  116. f"{Fore.GREEN}{ret[1]}{Style.RESET_ALL}",
  117. file,
  118. ])
  119. print(x)
  120. # Write the pickle
  121. with open(PICKLE_CACHE, "wb") as pfile:
  122. pickle.dump(json.dumps(METADATA_PATHS).encode(), pfile)
  123. if __name__ == "__main__":
  124. main()