cargo-outdated 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #!/usr/bin/env python3
  2. import json
  3. import pickle
  4. import subprocess
  5. from argparse import ArgumentParser
  6. from os import chdir, getenv
  7. from os.path import exists, join
  8. from subprocess import PIPE
  9. import semver
  10. import tomlkit
  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. # Yanked releases from crates.io to ignore
  21. YANKED = {"socket2": ["0.4.5"]}
  22. # Cached paths for metadata to not have to search through the crates index
  23. METADATA_PATHS = {}
  24. if exists(PICKLE_CACHE):
  25. with open(PICKLE_CACHE, "rb") as f:
  26. json_data = pickle.load(f)
  27. METADATA_PATHS = json.loads(json_data)
  28. def parse_toml(filename):
  29. with open(filename) as f:
  30. content = f.read()
  31. p = tomlkit.parse(content)
  32. deps = p.get("dependencies")
  33. devdeps = p.get("dev-dependencies")
  34. if deps and devdeps:
  35. dependencies = deps | devdeps
  36. elif deps:
  37. dependencies = deps
  38. elif devdeps:
  39. dependencies = devdeps
  40. else:
  41. dependencies = None
  42. return (p, dependencies)
  43. def get_metadata_path(name):
  44. find_output = subprocess.run(
  45. ["find", CRATESIO_INDEX, "-type", "f", "-name", name], stdout=PIPE)
  46. metadata_path = find_output.stdout.decode().strip()
  47. if metadata_path == '':
  48. return None
  49. # Place the path into cache
  50. METADATA_PATHS[name] = metadata_path
  51. return metadata_path
  52. def check_dep(name, data):
  53. if name in IGNORES:
  54. return None
  55. metadata_path = METADATA_PATHS.get(name)
  56. if not metadata_path:
  57. metadata_path = get_metadata_path(name)
  58. if not metadata_path:
  59. print(f"No crate found for {Fore.YELLOW}{name}{Style.RESET_ALL}")
  60. return None
  61. # Read the metadata. It's split as JSON objects, each in its own line.
  62. with open(metadata_path, encoding="utf-8") as f:
  63. lines = f.readlines()
  64. lines = [i.strip() for i in lines]
  65. # Latest one is at the end
  66. metadata = json.loads(lines[-1])
  67. # Get the version from the local data
  68. if isinstance(data, str):
  69. # This is just the semver
  70. local_version = data
  71. elif isinstance(data, dict):
  72. local_version = data.get("version")
  73. if not local_version:
  74. # Not a versioned dependency (can be path/git/...)
  75. return None
  76. else:
  77. raise ValueError(f"Invalid dependency: {name}")
  78. if semver.compare(local_version, metadata["vers"], loose=True) < 0:
  79. name = metadata["name"]
  80. vers = metadata["vers"]
  81. if name in YANKED and vers in YANKED[name]:
  82. return None
  83. return (local_version, vers)
  84. return None
  85. def main():
  86. parser = ArgumentParser(
  87. description="Prettyprint outdated dependencies in a cargo project")
  88. parser.add_argument("-u",
  89. "--update",
  90. action="store_true",
  91. help="Prompt to update dependencies")
  92. parser.add_argument("-i",
  93. "--ignore",
  94. type=str,
  95. help="Comma-separated list of deps to ignore")
  96. args = parser.parse_args()
  97. if args.ignore:
  98. for i in args.ignore.split(","):
  99. IGNORES.add(i)
  100. if not exists(CRATESIO_INDEX):
  101. print("Cloning crates.io index...")
  102. subprocess.run(["git", "clone", CRATESIO_REPO, CRATESIO_INDEX],
  103. capture_output=False)
  104. print("Updating crates.io index...")
  105. subprocess.run(["git", "-C", CRATESIO_INDEX, "fetch", "-a"],
  106. capture_output=False)
  107. subprocess.run(
  108. ["git", "-C", CRATESIO_INDEX, "reset", "--hard", "origin/master"],
  109. capture_output=False)
  110. # chdir to the root of the project
  111. toplevel = subprocess.run(["git", "rev-parse", "--show-toplevel"],
  112. capture_output=True)
  113. toplevel = toplevel.stdout.decode().strip()
  114. chdir(toplevel)
  115. find_output = subprocess.run(
  116. ["find", ".", "-type", "f", "-name", "Cargo.toml"], stdout=PIPE)
  117. files = [i.strip() for i in find_output.stdout.decode().split("\n")][:-1]
  118. x = PrettyTable()
  119. x.field_names = ["package", "crate", "current", "latest", "path"]
  120. for filename in files:
  121. ps, deps = parse_toml(filename)
  122. package = ps["package"]["name"]
  123. print(f"Checking deps for {Fore.GREEN}{package}{Style.RESET_ALL}")
  124. for dep in deps:
  125. ret = check_dep(dep, deps[dep])
  126. if ret:
  127. x.add_row([
  128. package,
  129. dep,
  130. f"{Fore.YELLOW}{ret[0]}{Style.RESET_ALL}",
  131. f"{Fore.GREEN}{ret[1]}{Style.RESET_ALL}",
  132. filename,
  133. ])
  134. if args.update and ret:
  135. print(f"Update {dep} from {ret[0]} to {ret[1]}? (y/N): ",
  136. end="")
  137. choice = input()
  138. if choice and (choice == "y" or choice == "Y"):
  139. if "dependencies" in ps and dep in ps["dependencies"]:
  140. if ps["dependencies"][dep] == ret[0]:
  141. ps["dependencies"][dep] = ret[1]
  142. else:
  143. ps["dependencies"][dep]["version"] = ret[1]
  144. elif "dev-dependencies" in ps and dep in ps[
  145. "dev-dependencies"]:
  146. if ps["dev-dependencies"][dep] == ret[0]:
  147. ps["dev-dependencies"][dep] = ret[1]
  148. else:
  149. ps["dev-dependencies"][dep]["version"] = ret[1]
  150. if args.update:
  151. with open(filename, "w") as f:
  152. f.write(tomlkit.dumps(ps))
  153. print(x)
  154. # Write the pickle
  155. with open(PICKLE_CACHE, "wb") as pfile:
  156. pickle.dump(json.dumps(METADATA_PATHS).encode(), pfile)
  157. if __name__ == "__main__":
  158. main()