Merging two directories with their CID?

Hi folks,

I have a question that is there a way other than manual do it to merge two folder using their cid? Like folder with cid xxx has file abc, and folder with cid yyy has file def, something command like ipfs merge xxx yyy will give cid zzz that contains file abcdef? Assume there are no conflict file, or with a merging option.

Thanks

3 Likes

I don’t think this feature is built-in so I threw this Python script together, hope it helps!

#!/usr/bin/env python
import requests, json, sys

# Usage: ipfs_merge_dir.py <dir1> <dir2> [dir3 dir4...]

# Address of node to use
NODE = "http://localhost:5001"

# API
API = "/api/v0/"
# TempDir
TEMP = "/merge_tmp"

# Creates temp dir in MFS, removing existing one if present
def MkTempDir():
	RmTempDir()
	req = requests.post(NODE+API+"files/mkdir?arg="+TEMP)
	
# Removes temp dir (and contents) from MFS
def RmTempDir():
	req = requests.post(NODE+API+"files/rm?arg=%s&force=true" % TEMP)

# Returns CID of the temp dir
def CIDTempDir():
	req = requests.post(NODE+API+"files/stat?arg=" + TEMP)
	data = json.loads(req.text)
	return data["Hash"]

# Copies contents of CIDs to temp dir
def CpCIDs(cids):
	req = requests.post(NODE+API+"ls?arg="+cids)
	dirData = json.loads(req.text)
	if "Type" in dirData and dirData["Type"] == "error":
		print(dirData["Message"])
		quit()

	for obj in dirData["Objects"]:
		if len(obj["Links"]) == 0:
			print("No links on CID, aborting: " + obj["Hash"])
			quit()
		if obj["Links"][0]["Name"] == "":
			print("Not a directory: " + obj["Hash"])
			quit()

		for i in obj["Links"]:
			req = requests.post(NODE+API+"files/cp?arg=/ipfs/%s&arg=%s/%s" % (i["Hash"], TEMP, i["Name"]))
			if req.text != "":
				print(req.text)

# Parses directories to merge together
def parseFlags():
	if len(sys.argv) < 3:
		print("Usage: ipfs_merge_dir.py <dir1> <dir2> [dir3 dir4...]")
		quit()
	cids = sys.argv[2:]
	out = sys.argv[1]
	for i in cids:
		out += "&arg="+i
	return out


# Main program
if __name__ == "__main__":
	cids = parseFlags()

	MkTempDir()
	CpCIDs(cids)
	print(CIDTempDir())
	RmTempDir()
1 Like

this is a very needed feature , didn’t you ask them to include it in the IPFS ?

1 Like

If this is something people commonly want to do often, I could open an issue and see what the devs think about it :slight_smile:.

1 Like