package com.semmle.js.extractor;

import com.semmle.util.exception.UserError;
import com.semmle.util.process.Env;
import com.semmle.util.process.Env.Var;

public class EnvironmentVariables {
  public static final String CODEQL_EXTRACTOR_JAVASCRIPT_ROOT_ENV_VAR =
      "CODEQL_EXTRACTOR_JAVASCRIPT_ROOT";
 
  public static final String CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR_ENV_VAR =
      "CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR";

  /**
   * Gets the extractor root based on the <code>CODEQL_EXTRACTOR_JAVASCRIPT_ROOT</code> or <code>
   * SEMMLE_DIST</code> or environment variable, or <code>null</code> if neither is set.
   */
  public static String tryGetExtractorRoot() {
    String env = Env.systemEnv().get(CODEQL_EXTRACTOR_JAVASCRIPT_ROOT_ENV_VAR);
    if (env != null && !env.isEmpty()) return env;
    env = Env.systemEnv().get(Var.SEMMLE_DIST);
    if (env != null && !env.isEmpty()) return env;
    return null;
  }

  /**
   * Gets the extractor root based on the <code>CODEQL_EXTRACTOR_JAVASCRIPT_ROOT</code> or <code>
   * SEMMLE_DIST</code> or environment variable, or throws a UserError if neither is set.
   */
  public static String getExtractorRoot() {
    String env = tryGetExtractorRoot();
    if (env == null) {
      throw new UserError("SEMMLE_DIST or CODEQL_EXTRACTOR_JAVASCRIPT_ROOT must be set");
    }
    return env;
  }

  public static String getScratchDir() {
    String env = Env.systemEnv().get(CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR_ENV_VAR);
    if (env == null) {
      throw new UserError(CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR_ENV_VAR + " must be set");
    }
    return env;
  }
}

@@ -429,16 +429,95 @@
 _DIR%22;%0A%0A
+  public static final String LGTM_WORKSPACE_ENV_VAR =%0A      %22LGTM_WORKSPACE%22;%0A%0A
   /**%0A  
@@ -782,32 +782,40 @@
 .systemEnv().get
+NonEmpty
 (CODEQL_EXTRACTO
@@ -861,34 +861,16 @@
  != null
- && !env.isEmpty()
 ) return
@@ -904,16 +904,24 @@
 nv().get
+NonEmpty
 (Var.SEM
@@ -954,26 +954,8 @@
 null
- && !env.isEmpty()
 ) re
@@ -1410,16 +1410,103 @@
 v;%0A  %7D%0A%0A
+  /**%0A   * Gets the scratch directory from the appropriate environment variable.%0A   */%0A
   public
@@ -1574,16 +1574,24 @@
 nv().get
+NonEmpty
 (CODEQL_
@@ -1641,33 +1641,33 @@
     if (env 
-=
+!
 = null) 
 %7B%0A      thro
@@ -1646,36 +1646,141 @@
 f (env != null) 
-%7B%0A  
+return env;%0A    env = Env.systemEnv().getNonEmpty(LGTM_WORKSPACE_ENV_VAR);%0A    if (env != null) return env;%0A%0A
     throw new Us
@@ -1843,43 +1843,55 @@
 + %22 
-must be set%22);%0A    %7D%0A    return env
+or %22 + LGTM_WORKSPACE_ENV_VAR + %22 must be set%22)
 ;%0A  

Handle LGTM_WORKSPACE and fix emptiness check