Hash :
28316df2
Author :
Thomas de Grivel
Date :
2022-04-02T19:37:40
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
defmodule DartSass do
@moduledoc """
DartSass is a installer and runner for [Sass](https://sass-lang.com/dart-sass).
## Profiles
You can define multiple configuration profiles. By default, there is a
profile called `:default` which you can configure its args, current
directory and environment:
config :dart_sass,
version: "1.49.0",
default: [
args: ~w(css/app.scss ../priv/static/assets/app.css),
cd: Path.expand("../assets", __DIR__)
]
## Dart Sass configuration
There are two global configurations for the `dart_sass` application:
* `:version` - the expected Sass version.
* `:path` - the path to the Sass executable. By default
it is automatically downloaded and placed inside the `_build` directory
of your current app. Note that if your system architecture requires a
separate Dart VM executable to run, then `:path` should be defined as a
list of absolute paths.
Overriding the `:path` is not recommended, as we will automatically
download and manage `sass` for you. But in case you can't download
it (for example, the GitHub releases are behind a proxy), you may want to
set the `:path` to a configurable system location.
For instance, you can install `sass` globally with `npm`:
$ npm install -g sass
Then the executable will be at:
NPM_ROOT/sass/sass.js
Where `NPM_ROOT` is the result of `npm root -g`.
Once you find the location of the executable, you can store it in a
`MIX_SASS_PATH` environment variable, which you can then read in
your configuration file:
config :dart_sass, path: System.get_env("MIX_SASS_PATH")
"""
use Application
require Logger
@doc false
def start(_, _) do
unless Application.get_env(:dart_sass, :version) do
Logger.warn("""
dart_sass version is not configured. Please set it in your config files:
config :dart_sass, :version, "#{latest_version()}"
""")
end
configured_version = configured_version()
case bin_version() do
{:ok, ^configured_version} ->
:ok
{:ok, version} ->
Logger.warn("""
Outdated dart-sass version. Expected #{configured_version}, got #{version}. \
Please run `mix sass.install` or update the version in your config files.\
""")
:error ->
:ok
end
Supervisor.start_link([], strategy: :one_for_one)
end
@doc false
# Latest known version at the time of publishing.
def latest_version do
"1.49.0"
end
@doc """
Returns the configured Sass version.
"""
def configured_version do
Application.get_env(:dart_sass, :version, latest_version())
end
@doc """
Returns the configuration for the given profile.
Returns nil if the profile does not exist.
"""
def config_for!(profile) when is_atom(profile) do
Application.get_env(:dart_sass, profile) ||
raise ArgumentError, """
unknown dart_sass profile. Make sure the profile named #{inspect(profile)} is defined in your config files, such as:
config :dart_sass,
#{profile}: [
args: ~w(css/app.scss:../priv/static/assets/app.css),
cd: Path.expand("../assets", __DIR__)
]
"""
end
@doc """
Returns the path to the `sass` executable.
Depending on your system target architecture, the path may be
preceeded by the path to the Dart VM executable.
"""
def bin_path do
env_path = Application.get_env(:dart_sass, :path)
if env_path do
List.wrap(env_path)
else
platform = platform()
cond do
Code.ensure_loaded?(Mix.Project) ->
bin_path(platform, Path.dirname(Mix.Project.build_path()))
true ->
bin_path(platform, "_build")
end
end
end
# TODO: Remove when dart-sass will exit when stdin is closed.
@doc false
def script_path() do
Path.join(:code.priv_dir(:dart_sass), "dart_sass.ksh")
end
@doc """
Returns the version of the Sass executable (or snapshot).
Returns `{:ok, version_string}` on success or `:error` when the executable
is not available.
"""
def bin_version do
path = bin_path()
with true <- path_exists?(path),
{result, 0} <- cmd(path, ["--version"]) do
{:ok, String.trim(result)}
else
_ -> :error
end
end
defp cmd(path, args) do
cmd(path, args, [])
end
defp cmd([command | args], extra_args, opts) do
System.cmd(command, args ++ extra_args, opts)
end
@doc """
Runs the given command with `args`.
The given args will be appended to the configured args.
The task output will be streamed directly to stdio. It
returns the status of the underlying call.
"""
def run(profile, extra_args) when is_atom(profile) and is_list(extra_args) do
config = config_for!(profile)
config_args = config[:args] || []
opts = [
cd: config[:cd] || File.cwd!(),
env: config[:env] || %{},
into: IO.stream(:stdio, :line),
stderr_to_stdout: true
]
args = config_args ++ extra_args
path = bin_path()
# TODO: Remove when dart-sass will exit when stdin is closed.
# Link: https://github.com/sass/dart-sass/pull/1411
path =
if "--watch" in args and platform() != :windows do
[script_path() | path]
else
path
end
path
|> cmd(args, opts)
|> elem(1)
end
@doc """
Installs, if not available, and then runs `sass`.
Returns the same as `run/2`.
"""
def install_and_run(profile, args) do
unless path_exists?(bin_path()) do
install()
end
run(profile, args)
end
@doc """
Installs dart-sass with `configured_version/0`.
"""
def install do
version = configured_version()
tmp_opts = if System.get_env("MIX_XDG"), do: %{os: :linux}, else: %{}
tmp_dir =
freshdir_p(:filename.basedir(:user_cache, "cs-sass", tmp_opts)) ||
freshdir_p(Path.join(System.tmp_dir!(), "cs-sass")) ||
raise "could not install sass. Set MIX_XDG=1 and then set XDG_CACHE_HOME to the path you want to use as cache"
platform = platform()
name = "dart-sass-#{version}-#{target_extname(platform)}"
url = "https://github.com/sass/dart-sass/releases/download/#{version}/#{name}"
archive = fetch_body!(url)
case unpack_archive(Path.extname(name), archive, tmp_dir) do
:ok -> :ok
other -> raise "couldn't unpack archive: #{inspect(other)}"
end
path = bin_path()
case platform do
:linux ->
[sass | _] = path
File.rm(sass)
File.cp!(Path.join([tmp_dir, "dart-sass", "sass"]), sass)
:macos ->
[dart, snapshot | _] = path
File.rm(dart)
File.cp!(Path.join([tmp_dir, "dart-sass", "src", "dart"]), dart)
File.rm(snapshot)
File.cp!(Path.join([tmp_dir, "dart-sass", "src", "sass.snapshot"]), snapshot)
:windows ->
[dart, snapshot | _] = path
File.rm(dart)
File.cp!(Path.join([tmp_dir, "dart-sass", "src", "dart.exe"]), dart)
File.rm(snapshot)
File.cp!(Path.join([tmp_dir, "dart-sass", "src", "sass.snapshot"]), snapshot)
end
end
defp bin_path(platform, base_path) do
target = target(platform)
case platform do
:linux ->
[Path.join(base_path, "sass-#{target}")]
_ ->
[
Path.join(base_path, "dart-#{target}"),
Path.join(base_path, "sass.snapshot-#{target}")
]
end
end
defp platform do
case :os.type() do
{:unix, :darwin} -> :macos
{:unix, :linux} -> :linux
{:unix, osname} -> raise "dart_sass is not available for osname: #{inspect(osname)}"
{:win32, _} -> :windows
end
end
defp path_exists?(path) do
Enum.all?(path, &File.exists?/1)
end
defp freshdir_p(path) do
with {:ok, _} <- File.rm_rf(path),
:ok <- File.mkdir_p(path) do
path
else
_ -> nil
end
end
defp unpack_archive(".zip", zip, cwd) do
with {:ok, _} <- :zip.unzip(zip, cwd: to_charlist(cwd)), do: :ok
end
defp unpack_archive(_, tar, cwd) do
:erl_tar.extract({:binary, tar}, [:compressed, cwd: to_charlist(cwd)])
end
defp target_extname(platform) do
target = target(platform)
case platform do
:windows -> "#{target}.zip"
_ -> "#{target}.tar.gz"
end
end
# Available targets: https://github.com/sass/dart-sass/releases
defp target(:windows) do
case :erlang.system_info(:wordsize) * 8 do
32 -> "windows-ia32"
64 -> "windows-x64"
end
end
defp target(platform) do
arch_str = :erlang.system_info(:system_architecture)
[arch | _] = arch_str |> List.to_string() |> String.split("-")
# TODO: remove "arm" when we require OTP 24
arch =
if platform == :macos and arch in ["aarch64", "arm"] do
# Using Rosetta2 for M1 until sass/dart-sass runs native
# Link: https://github.com/sass/dart-sass/issues/1125
"amd64"
else
arch
end
case arch do
"amd64" -> "#{platform}-x64"
"x86_64" -> "#{platform}-x64"
"i686" -> "#{platform}-ia32"
"i386" -> "#{platform}-ia32"
_ -> raise "dart_sass not available for architecture: #{arch_str}"
end
end
defp fetch_body!(url) do
url = String.to_charlist(url)
Logger.debug("Downloading dart-sass from #{url}")
{:ok, _} = Application.ensure_all_started(:inets)
{:ok, _} = Application.ensure_all_started(:ssl)
if proxy = System.get_env("HTTP_PROXY") || System.get_env("http_proxy") do
Logger.debug("Using HTTP_PROXY: #{proxy}")
%{host: host, port: port} = URI.parse(proxy)
:httpc.set_options([{:proxy, {{String.to_charlist(host), port}, []}}])
end
if proxy = System.get_env("HTTPS_PROXY") || System.get_env("https_proxy") do
Logger.debug("Using HTTPS_PROXY: #{proxy}")
%{host: host, port: port} = URI.parse(proxy)
:httpc.set_options([{:https_proxy, {{String.to_charlist(host), port}, []}}])
end
# https://erlef.github.io/security-wg/secure_coding_and_deployment_hardening/inets
cacertfile = cacertfile() |> String.to_charlist()
http_options = [
autoredirect: false,
ssl: [
verify: :verify_peer,
cacertfile: cacertfile,
depth: 2,
customize_hostname_check: [
match_fun: :public_key.pkix_verify_hostname_match_fun(:https)
]
]
]
case :httpc.request(:get, {url, []}, http_options, []) do
{:ok, {{_, 302, _}, headers, _}} ->
{'location', download} = List.keyfind(headers, 'location', 0)
options = [body_format: :binary]
case :httpc.request(:get, {download, []}, http_options, options) do
{:ok, {{_, 200, _}, _, body}} ->
body
other ->
raise "couldn't fetch #{download}: #{inspect(other)}"
end
other ->
raise "couldn't fetch #{url}: #{inspect(other)}"
end
end
defp cacertfile() do
Application.get_env(:dart_sass, :cacerts_path) || CAStore.file_path()
end
end