Skip to content

Instantly share code, notes, and snippets.

@gm10
Created December 10, 2018 09:37
Show Gist options
  • Save gm10/af75129e6b3dc5d629f0106aa8c143e3 to your computer and use it in GitHub Desktop.
Save gm10/af75129e6b3dc5d629f0106aa8c143e3 to your computer and use it in GitHub Desktop.
Recursively add all new images in a given path to ~/.config/mate/backgrounds.xml
#!/usr/bin/python3
"""
Recursively adds all new images in a given path to ~/.config/mate/backgrounds.xml
"""
import os, sys
from pathlib import Path
import mimetypes
if not len(sys.argv) == 2 or not os.path.exists(sys.argv[1]):
print("Argument must be a valid path")
sys.exit(1)
template = """\
<wallpaper deleted="false">
<name>%s</name>
<filename>%s</filename>
<options>zoom</options>
<shade_type>solid</shade_type>
<pcolor>rgb(0,0,0)</pcolor>
<scolor>rgb(0,0,0)</scolor>
<artist>(unknown)</artist>
</wallpaper>
"""
backgrounds_file = os.path.join(Path.home(), ".config/mate/backgrounds.xml")
if os.path.exists(backgrounds_file):
xml = open(backgrounds_file).readlines()
else:
xml = ['<?xml version="1.0"?>\n','<!DOCTYPE wallpapers SYSTEM "mate-wp-list.dtd">\n','<wallpapers>\n','</wallpapers>\n']
files = list(Path(sys.argv[1]).rglob("**/*"))
knownfiles = [line.partition("<filename>")[2].partition("</filename>")[0] for line in xml if "<filename>" in line]
output = ""
count = 0
for filename in files:
if not str(filename) in knownfiles:
filetype = mimetypes.guess_type(os.path.abspath(filename))[0]
if filetype and "image" in str(filetype):
output += template % (os.path.basename(filename), filename)
count += 1
if count:
for i, line in enumerate(xml):
if line.strip() == "</wallpapers>":
xml.insert(i, output)
break
with open(backgrounds_file, "w") as f:
f.write("".join(xml))
print("%d new background images added successfully" % count)
else:
print("No new background images found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment